@mulmoclaude/core 7.6.0 → 7.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/assets/helps/bug-report-faq.md +7 -7
  2. package/dist/collection/index.cjs +3 -3
  3. package/dist/collection/index.js +3 -3
  4. package/dist/collection/registry/server/index.cjs +3 -3
  5. package/dist/collection/registry/server/index.js +3 -3
  6. package/dist/collection/server/index.cjs +2 -2
  7. package/dist/collection/server/index.js +2 -2
  8. package/dist/collection-watchers/index.cjs +4 -4
  9. package/dist/collection-watchers/index.js +4 -4
  10. package/dist/{discovery-BSvWBOGB.cjs → discovery-D1cjgQRo.cjs} +4 -4
  11. package/dist/discovery-D1cjgQRo.cjs.map +1 -0
  12. package/dist/{discovery-DEhLlDVW.js → discovery-c5OKO0dI.js} +4 -4
  13. package/dist/discovery-c5OKO0dI.js.map +1 -0
  14. package/dist/{dist-CdSEjlVx.cjs → dist--k7dcIzm.cjs} +2 -2
  15. package/dist/dist--k7dcIzm.cjs.map +1 -0
  16. package/dist/{dist--searOB5.js → dist-Cb-KNFRA.js} +2 -2
  17. package/dist/dist-Cb-KNFRA.js.map +1 -0
  18. package/dist/errorMessage-BDEhi5qf.cjs +1 -0
  19. package/dist/errorMessage-BFkRmkyh.js +1 -0
  20. package/dist/{errors-BbH5CeKm.js → errors-D-LZwNSI.js} +2 -2
  21. package/dist/{errors-BbH5CeKm.js.map → errors-D-LZwNSI.js.map} +1 -1
  22. package/dist/{errors-B7ShVbIB.cjs → errors-DVKixTWx.cjs} +2 -2
  23. package/dist/{errors-B7ShVbIB.cjs.map → errors-DVKixTWx.cjs.map} +1 -1
  24. package/dist/feeds/server/index.cjs +5 -5
  25. package/dist/feeds/server/index.cjs.map +1 -1
  26. package/dist/feeds/server/index.js +5 -5
  27. package/dist/feeds/server/index.js.map +1 -1
  28. package/dist/google/index.cjs +3 -3
  29. package/dist/google/index.js +3 -3
  30. package/dist/{listen-OGOFPIdk.cjs → listen-Bu1QX69l.cjs} +2 -2
  31. package/dist/{listen-OGOFPIdk.cjs.map → listen-Bu1QX69l.cjs.map} +1 -1
  32. package/dist/{listen-Bm8N0g9o.js → listen-CPZX9gpR.js} +2 -2
  33. package/dist/{listen-Bm8N0g9o.js.map → listen-CPZX9gpR.js.map} +1 -1
  34. package/dist/notifier/index.cjs +1 -1
  35. package/dist/notifier/index.js +1 -1
  36. package/dist/{notifier-D7TmVus0.js → notifier-B3cqvwts.js} +2 -2
  37. package/dist/{notifier-D7TmVus0.js.map → notifier-B3cqvwts.js.map} +1 -1
  38. package/dist/{notifier-8R05SHLj.cjs → notifier-Cq2UbCTW.cjs} +2 -2
  39. package/dist/{notifier-8R05SHLj.cjs.map → notifier-Cq2UbCTW.cjs.map} +1 -1
  40. package/dist/plugin-vue/index.cjs +1 -1
  41. package/dist/plugin-vue/index.cjs.map +1 -1
  42. package/dist/plugin-vue/index.js +1 -1
  43. package/dist/plugin-vue/index.js.map +1 -1
  44. package/dist/prompt-files/index.cjs +1 -1
  45. package/dist/prompt-files/index.js +1 -1
  46. package/dist/{promptSafety-CYU_kLUL.js → promptSafety-B_Jbtlcb.js} +2 -2
  47. package/dist/{promptSafety-CYU_kLUL.js.map → promptSafety-B_Jbtlcb.js.map} +1 -1
  48. package/dist/{promptSafety-CF6OCtor.cjs → promptSafety-Ctl7rOvA.cjs} +2 -2
  49. package/dist/{promptSafety-CF6OCtor.cjs.map → promptSafety-Ctl7rOvA.cjs.map} +1 -1
  50. package/dist/remote-host/index.cjs +1 -1
  51. package/dist/remote-host/index.js +1 -1
  52. package/dist/remote-host/server/index.cjs +4 -4
  53. package/dist/remote-host/server/index.js +4 -4
  54. package/dist/{remote-host-BiCg_ioB.js → remote-host-DyAlq52o.js} +2 -2
  55. package/dist/{remote-host-BiCg_ioB.js.map → remote-host-DyAlq52o.js.map} +1 -1
  56. package/dist/{remote-host-neXWDACl.cjs → remote-host-gvsvPRli.cjs} +2 -2
  57. package/dist/{remote-host-neXWDACl.cjs.map → remote-host-gvsvPRli.cjs.map} +1 -1
  58. package/dist/remote-view/index.cjs +1 -1
  59. package/dist/remote-view/index.js +1 -1
  60. package/dist/runtime-plugins/extract.d.ts +6 -0
  61. package/dist/runtime-plugins/index.cjs +95 -15
  62. package/dist/runtime-plugins/index.cjs.map +1 -1
  63. package/dist/runtime-plugins/index.js +96 -16
  64. package/dist/runtime-plugins/index.js.map +1 -1
  65. package/dist/runtime-plugins/install.d.ts +2 -1
  66. package/dist/runtime-plugins/load.d.ts +2 -5
  67. package/dist/scheduler/index.cjs +2 -2
  68. package/dist/scheduler/index.js +2 -2
  69. package/dist/{server-BxwOUg_l.cjs → server-B6usmOfY.cjs} +5 -5
  70. package/dist/{server-BxwOUg_l.cjs.map → server-B6usmOfY.cjs.map} +1 -1
  71. package/dist/{server-C3HNV-PG.js → server-CtghuxhH.js} +5 -5
  72. package/dist/{server-C3HNV-PG.js.map → server-CtghuxhH.js.map} +1 -1
  73. package/dist/utils/index.cjs +2 -2
  74. package/dist/utils/index.js +2 -2
  75. package/dist/whisper/index.cjs +2 -2
  76. package/dist/whisper/index.js +2 -2
  77. package/dist/wiki/index.cjs +1 -1
  78. package/dist/wiki/index.js +1 -1
  79. package/dist/workspace-setup/index.js +1 -1
  80. package/dist/workspace-setup/index.js.map +1 -1
  81. package/package.json +1 -1
  82. package/dist/discovery-BSvWBOGB.cjs.map +0 -1
  83. package/dist/discovery-DEhLlDVW.js.map +0 -1
  84. package/dist/dist--searOB5.js.map +0 -1
  85. package/dist/dist-CdSEjlVx.cjs.map +0 -1
  86. package/dist/errorMessage-B-iVKe5R.cjs +0 -1
  87. package/dist/errorMessage-D-HWCI2W.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"remote-host-neXWDACl.cjs","names":["isRecord"],"sources":["../src/remote-host/health.ts","../src/remote-host/index.ts"],"sourcesContent":["// Health of the remote-host command channel, as reported by the resilient runner\n// and rendered by a host's toolbar control. Browser-safe on purpose: the client\n// narrows the parsed HTTP payload with the same guard the server writes it from,\n// so the two sides cannot drift on the state names.\n//\n// online — the Firestore subscription is up; the phone can reach this host\n// reconnecting — it died and is being re-subscribed with backoff (self-healing)\n// offline — re-subscribing stopped helping, or nothing is connected at all;\n// recovering needs a re-auth from the browser's parked session\n//\n// Deliberately no UI wording here — how a state reads to a user is each host's\n// i18n, and core owning it would make the shared package a translation authority.\nexport const RUNNER_HEALTH_STATES = [\"online\", \"reconnecting\", \"offline\"] as const;\nexport type RunnerHealthState = (typeof RUNNER_HEALTH_STATES)[number];\n\nexport interface RunnerHealth {\n state: RunnerHealthState;\n /** Last channel error seen, for the popover and the log. Null before the first one. */\n lastError: string | null;\n /** ms epoch of the last state change, so the UI can say how long it has been down. */\n changedAt: number;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null;\n\nexport const isRunnerHealthState = (value: unknown): value is RunnerHealthState => RUNNER_HEALTH_STATES.some((state) => state === value);\n\n/** Narrows a parsed HTTP payload. The client renders whatever this accepts, so a\n * half-shaped health has to read as \"no health reported\" rather than as a state. */\nexport const isRunnerHealth = (value: unknown): value is RunnerHealth =>\n isRecord(value) &&\n isRunnerHealthState(value.state) &&\n (value.lastError === null || typeof value.lastError === \"string\") &&\n typeof value.changedAt === \"number\";\n","// Remote-host command-channel protocol — the browser-safe contract shared by a\n// host (MulmoClaude, MulmoTerminal) and the remote/mobile client (mulmoserver).\n//\n// A host signs in to Firebase as the user, listens to that user's per-host\n// command queue in Firestore, runs a handler, and writes the result back; the\n// remote writes commands and reads results via a real-time listener. This module\n// owns the wire types + pure helpers, and must load without the Firebase SDK; the\n// Firestore path helpers live in `./server/paths.ts`. It is the single source of\n// truth so the host runner and the client never drift on the protocol.\n//\n// Ported from ../mulmoserver/src/firestore/commandChannel.ts and the per-host\n// copy that lived in MulmoClaude's server/remoteHost/. The hostId is\n// host-specific (\"mulmoclaude\", \"mulmoterminal\") and is supplied by each host.\nimport { isRecord } from \"@mulmoclaude/common\";\n\n// JSON payloads carried by the command channel. Explicit JSON types keep the\n// channel typed without resorting to any/unknown.\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\nexport type JsonObject = Record<string, JsonValue>;\n\n/** Structural JSON view of `T`, recursively.\n *\n * TypeScript gives an implicit index signature to type aliases and mapped\n * types but NOT to interfaces, so a payload assembled from domain interfaces\n * (`Shortcut`, `FeedSummary`, …) cannot satisfy `Record<string, JsonValue>`\n * structurally — even though it is plain JSON at runtime. Mapping over `T`\n * reconstructs it as an anonymous type, which does get that index signature.\n *\n * Recursive on purpose: a top-level-only map would still leave nested\n * interfaces (`{ shortcuts: Shortcut[] }`) unassignable, which is the case\n * every handler here actually has. */\n// The function branch must come BEFORE the object branch: a function IS an\n// object to TypeScript, so without it a function maps to `{}` and sails\n// through — the helper would accept a payload that serialises to nothing.\n// Verified: `toJsonObject({ callback: () => undefined })` compiled clean until\n// this branch existed (CodeRabbit, #2596).\nexport type Jsonify<T> = T extends JsonValue\n ? T\n : T extends (...args: never[]) => unknown\n ? never\n : T extends (infer U)[]\n ? Jsonify<U>[]\n : T extends object\n ? { [K in keyof T]: Jsonify<T[K]> }\n : never;\n\n/** Widen a JSON-shaped handler payload to the channel's `JsonObject`.\n *\n * Exists so the `Jsonify` reasoning above lives in ONE place. Before this,\n * eight remote-host handlers each carried their own `as unknown as JsonObject`\n * with the justification re-argued in eight slightly different comments —\n * which is how a rule stops being reviewable. */\nexport const toJsonObject = <T extends object>(payload: Jsonify<T>): JsonObject => payload as JsonObject;\n\nconst describeNonJson = (value: unknown): string => {\n if (typeof value === \"number\") return String(value);\n if (typeof value === \"object\") return \"a non-plain object\";\n return `a ${typeof value}`;\n};\n\n/** Anything carrying its own JSON form — `Date` above all — must be asked for\n * it rather than walked, because walking a `Date`'s own enumerable keys finds\n * none and flattens the timestamp to `{}`. This is the step `JSON.stringify`\n * performs before it recurses, and the channel used to get it for free. */\nconst hasToJson = (value: object): value is { toJSON: () => unknown } => \"toJSON\" in value && typeof value.toJSON === \"function\";\n\nconst jsonRepresentationOf = (value: object): unknown => (hasToJson(value) ? value.toJSON() : value);\n\n/** Rebuild `value` as JSON, or throw naming the property that cannot be. */\nfunction toJsonValue(value: unknown, path: string): JsonValue {\n if (Array.isArray(value)) return toJsonItems(value, path);\n if (isRecord(value)) {\n const represented = jsonRepresentationOf(value);\n if (represented !== value) return toJsonValue(represented, path);\n return toJsonEntries(value, path);\n }\n return toJsonScalar(value, path);\n}\n\n/** JSON's four scalar forms. Anything else — a function, a class instance, a\n * non-finite number — is what the channel cannot carry. */\nfunction toJsonScalar(value: unknown, path: string): JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n throw new Error(`${path} is ${describeNonJson(value)}, which JSON cannot represent`);\n}\n\nfunction toJsonItems(items: unknown[], path: string): JsonValue[] {\n // An absent element becomes `null`, matching `JSON.stringify` — an array has\n // to keep its length, so a hole cannot simply be dropped the way a key is.\n // `Array.from` rather than `map`, which SKIPS holes and would leave them in\n // the result: `JSON.stringify` renders a hole as null and hides that, but\n // `1 in arr` / `Object.keys` / `forEach` all still see the gap.\n return Array.from(items, (entry, index) => (entry === undefined ? null : toJsonValue(entry, `${path}[${index}]`)));\n}\n\nfunction toJsonEntries(record: Record<string, unknown>, path: string): JsonObject {\n const usable = Object.entries(record).filter(([, value]) => value !== undefined);\n return Object.fromEntries(usable.map(([key, value]) => [key, toJsonValue(value, `${path}.${key}`)]));\n}\n\n/** Runtime counterpart to `toJsonObject`, for payloads whose values are typed\n * `unknown` — a collection record, a projected view row — so no amount of\n * mapped-type work can PROVE them JSON.\n *\n * Walks the payload and rebuilds it from the values it actually inspected, so\n * the returned `JsonObject` is earned rather than asserted. Absent (`undefined`)\n * properties are dropped exactly as `JSON.stringify` drops them; anything the\n * channel could not carry — a function, a class instance, `NaN` — throws\n * naming its path, instead of reaching Firestore as a silently mangled write. */\nexport const coerceJsonObject = (payload: Record<string, unknown>): JsonObject => toJsonEntries(payload, \"payload\");\n\n// A channel routes commands to one specific host. A host's first machine uses the\n// host's fixed id (\"mulmoclaude\", \"mulmoterminal\"); a host that runs on several\n// machines gives each later one \"<id>-<8 hex>\" (RemoteHostDeps.resolveHostId), and\n// the remote finds those by listing users/{uid}/hosts.\nexport interface Channel {\n uid: string;\n hostId: string;\n}\n\nexport type CommandStatus = \"queued\" | \"processing\" | \"done\" | \"error\";\n\nexport interface CommandError {\n code: string;\n message: string;\n}\n\n// One document in a channel's commands subcollection is one API-call-like\n// request. The remote (mobile) writes method/params; the host writes\n// result/error/status.\nexport interface Command {\n method: string;\n params: JsonObject;\n status: CommandStatus;\n result: JsonValue;\n error: CommandError | null;\n createdBy: \"remote\" | \"host\";\n // Offline-queue fields (all optional; absent ⇒ pre-offline-queue behaviour, so\n // this is backward-compatible with every deployed client). Epoch-millisecond\n // NUMBERS set by the remote at enqueue time — deliberately plain numbers, not\n // Firestore Timestamps, so `isExpired` / `byCreatedAt` stay pure + browser-safe\n // and unit-testable without a Firestore fake. Clock skew over a multi-day expiry\n // window is immaterial. See plans/done/feat-remote-offline-queue.md.\n createdAt?: number; // enqueue time — age/display + best-effort dispatch bias (NOT a strict order guarantee; chat is async)\n expiresAt?: number; // deadline; past it the host deletes the command + its staged attachments\n queuedOffline?: boolean; // emitted while the host was offline (gates the remote's attachment rollback)\n}\n\n// A command is expired once `now` reaches its remote-set deadline. Absent\n// `expiresAt` ⇒ it never expires (pre-offline-queue commands). Pure with an\n// injected `now` for deterministic tests; the runner passes `Date.now()`.\nexport const isExpired = (command: Pick<Command, \"expiresAt\">, now: number): boolean => typeof command.expiresAt === \"number\" && now >= command.expiresAt;\n\n// Best-effort dispatch bias for a drained batch: oldest enqueue first. This is\n// NOT an ordering guarantee — commands run concurrently and may complete out of\n// order (chat is asynchronous, by design); it only nudges which one starts first.\n// A command with no `createdAt` sorts as oldest (0) so it is never starved.\nexport const byCreatedAt = (left: Pick<Command, \"createdAt\">, right: Pick<Command, \"createdAt\">): number => (left.createdAt ?? 0) - (right.createdAt ?? 0);\n\nexport type CommandHandler = (params: JsonObject) => JsonValue | Promise<JsonValue>;\nexport type CommandHandlers = Record<string, CommandHandler>;\n\n/** The param name a collection-serving command uses to say WHICH project's\n * collections it means. Reserved and documented now, before a phone client\n * ships, because the parts that are hard to change later are the ones being\n * written today. Four rules go with it:\n *\n * 1. **It is an OPAQUE scope, never a path.** The phone is a genuinely remote\n * client; an absolute root in a command, an artifact or a token publishes\n * the user's home directory over the wire. Mint a project id host-side and\n * resolve it host-side.\n * 2. **The phone must be able to LEARN the list.** A picker needs\n * `{ id, label }` pairs from the host — a command of its own, or a field on\n * an existing listing. Designing the scope value now is what keeps that the\n * ONLY new thing when the feature lands.\n * 3. **Handlers RESOLVE a scope; they do not hard-code one.** Write each\n * collection handler as \"read the scope from params, defaulting to the\n * host's root\" rather than calling the workspace accessor inline. Today\n * every call resolves the default and behaves exactly as it does now; the\n * day the param arrives, no handler changes.\n * 4. **The artifact stays host-built.** A remote view's srcdoc, its inlined\n * image thumbnails and its token are assembled on the host, so the phone\n * never resolves a path itself. That is what makes (1) hold without\n * trusting the client. */\nexport const COMMAND_SCOPE_PARAM = \"project\";\n\n/** Read the opaque project scope off a command's params, or `undefined` for\n * \"the host's own root\" — which is what every command means today. A\n * non-string (or empty) value is treated as absent rather than as an error: a\n * scope the host cannot resolve must fall back to the default, never to a\n * guess. Hosts pass the result to their own id → root resolver; this module\n * deliberately never sees a path. */\nexport const readCommandScope = (params: JsonObject): string | undefined => {\n const raw = params[COMMAND_SCOPE_PARAM];\n return typeof raw === \"string\" && raw.trim().length > 0 ? raw.trim() : undefined;\n};\n\n// Bumped when the command-channel wire protocol changes in a way the remote must\n// gate on. Advertised in the presence doc so the remote can check compatibility\n// before issuing commands.\n//\n// v2: offline queueing. The host honours `expiresAt` (deletes an expired command\n// + its staged attachments instead of spawning a stale chat). A remote MUST see\n// protocolVersion >= 2 before queueing a startChat while the host is offline —\n// a v1 host silently ignores `expiresAt`, so a queued chat would spawn stale on\n// reconnect with its uploads never cleaned up.\nexport const REMOTE_HOST_PROTOCOL_VERSION = 2;\n\n// The presence doc's payload: online flag + a capability advertisement. Written\n// by the host on every heartbeat; the remote reads it from the presence listener\n// it already runs (no extra round trip, known the instant the host is online).\n// Browser-safe so the mobile client compiles against the same shape.\n// `updatedAt` (a Firestore serverTimestamp) is added by the runner at write time\n// and is intentionally not part of this capability contract.\n// Which machine a presence comes from, for a host that can run on several machines\n// under one account (mulmoterminal#3092): a stable id the host recognises itself by,\n// and the name the remote shows for it.\nexport interface HostMachine {\n machineId: string;\n label: string;\n}\n\nexport interface HostPresence {\n online: boolean;\n hostId: string;\n protocolVersion: number;\n // Method names the host serves — the keys of the live handler table.\n capabilities: string[];\n machineId?: string;\n label?: string;\n}\n\n// Build the presence payload from the live handler table. Capabilities are\n// `Object.keys(handlers)` so registering a handler is the ONLY step needed to\n// advertise it — there is no second list to keep in sync.\nexport const buildHostPresence = (channel: Channel, handlers: CommandHandlers, online: boolean, machine?: HostMachine): HostPresence => ({\n online,\n hostId: channel.hostId,\n protocolVersion: REMOTE_HOST_PROTOCOL_VERSION,\n capabilities: Object.keys(handlers),\n ...(machine ? { machineId: machine.machineId, label: machine.label } : {}),\n});\n\n// Channel health as the resilient runner reports it. Browser-safe alongside the\n// wire types because the control that renders it runs in the client.\nexport { RUNNER_HEALTH_STATES, isRunnerHealth, isRunnerHealthState } from \"./health.js\";\nexport type { RunnerHealth, RunnerHealthState } from \"./health.js\";\n"],"mappings":";;AAYA,IAAa,uBAAuB;CAAC;CAAU;CAAgB;AAAS;AAWxE,IAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU;AAE9G,IAAa,uBAAuB,UAA+C,qBAAqB,MAAM,UAAU,UAAU,KAAK;;;AAIvI,IAAa,kBAAkB,UAC7B,SAAS,KAAK,KACd,oBAAoB,MAAM,KAAK,MAC9B,MAAM,cAAc,QAAQ,OAAO,MAAM,cAAc,aACxD,OAAO,MAAM,cAAc;;;;;;;;ACmB7B,IAAa,gBAAkC,YAAoC;AAEnF,IAAM,mBAAmB,UAA2B;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,KAAK,OAAO;AACrB;;;;;AAMA,IAAM,aAAa,UAAsD,YAAY,SAAS,OAAO,MAAM,WAAW;AAEtH,IAAM,wBAAwB,UAA4B,UAAU,KAAK,IAAI,MAAM,OAAO,IAAI;;AAG9F,SAAS,YAAY,OAAgB,MAAyB;CAC5D,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,YAAY,OAAO,IAAI;CACxD,IAAIA,aAAAA,SAAS,KAAK,GAAG;EACnB,MAAM,cAAc,qBAAqB,KAAK;EAC9C,IAAI,gBAAgB,OAAO,OAAO,YAAY,aAAa,IAAI;EAC/D,OAAO,cAAc,OAAO,IAAI;CAClC;CACA,OAAO,aAAa,OAAO,IAAI;AACjC;;;AAIA,SAAS,aAAa,OAAgB,MAAyB;CAC7D,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO;CACtF,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GAAG,OAAO;CAChE,MAAM,IAAI,MAAM,GAAG,KAAK,MAAM,gBAAgB,KAAK,EAAE,8BAA8B;AACrF;AAEA,SAAS,YAAY,OAAkB,MAA2B;CAMhE,OAAO,MAAM,KAAK,QAAQ,OAAO,UAAW,UAAU,KAAA,IAAY,OAAO,YAAY,OAAO,GAAG,KAAK,GAAG,MAAM,EAAE,CAAE;AACnH;AAEA,SAAS,cAAc,QAAiC,MAA0B;CAChF,MAAM,SAAS,OAAO,QAAQ,MAAM,CAAC,CAAC,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS;CAC/E,OAAO,OAAO,YAAY,OAAO,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,YAAY,OAAO,GAAG,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC;AACrG;;;;;;;;;;AAWA,IAAa,oBAAoB,YAAiD,cAAc,SAAS,SAAS;AA0ClH,IAAa,aAAa,SAAqC,QAAyB,OAAO,QAAQ,cAAc,YAAY,OAAO,QAAQ;AAMhJ,IAAa,eAAe,MAAkC,WAA+C,KAAK,aAAa,MAAM,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;AA2BxJ,IAAa,sBAAsB;;;;;;;AAQnC,IAAa,oBAAoB,WAA2C;CAC1E,MAAM,MAAM,OAAO;CACnB,OAAO,OAAO,QAAQ,YAAY,IAAI,KAAK,CAAC,CAAC,SAAS,IAAI,IAAI,KAAK,IAAI,KAAA;AACzE;AAWA,IAAa,+BAA+B;AA6B5C,IAAa,qBAAqB,SAAkB,UAA2B,QAAiB,aAAyC;CACvI;CACA,QAAQ,QAAQ;CAChB,iBAAA;CACA,cAAc,OAAO,KAAK,QAAQ;CAClC,GAAI,UAAU;EAAE,WAAW,QAAQ;EAAW,OAAO,QAAQ;CAAM,IAAI,CAAC;AAC1E"}
1
+ {"version":3,"file":"remote-host-gvsvPRli.cjs","names":["isRecord"],"sources":["../src/remote-host/health.ts","../src/remote-host/index.ts"],"sourcesContent":["// Health of the remote-host command channel, as reported by the resilient runner\n// and rendered by a host's toolbar control. Browser-safe on purpose: the client\n// narrows the parsed HTTP payload with the same guard the server writes it from,\n// so the two sides cannot drift on the state names.\n//\n// online — the Firestore subscription is up; the phone can reach this host\n// reconnecting — it died and is being re-subscribed with backoff (self-healing)\n// offline — re-subscribing stopped helping, or nothing is connected at all;\n// recovering needs a re-auth from the browser's parked session\n//\n// Deliberately no UI wording here — how a state reads to a user is each host's\n// i18n, and core owning it would make the shared package a translation authority.\nexport const RUNNER_HEALTH_STATES = [\"online\", \"reconnecting\", \"offline\"] as const;\nexport type RunnerHealthState = (typeof RUNNER_HEALTH_STATES)[number];\n\nexport interface RunnerHealth {\n state: RunnerHealthState;\n /** Last channel error seen, for the popover and the log. Null before the first one. */\n lastError: string | null;\n /** ms epoch of the last state change, so the UI can say how long it has been down. */\n changedAt: number;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null;\n\nexport const isRunnerHealthState = (value: unknown): value is RunnerHealthState => RUNNER_HEALTH_STATES.some((state) => state === value);\n\n/** Narrows a parsed HTTP payload. The client renders whatever this accepts, so a\n * half-shaped health has to read as \"no health reported\" rather than as a state. */\nexport const isRunnerHealth = (value: unknown): value is RunnerHealth =>\n isRecord(value) &&\n isRunnerHealthState(value.state) &&\n (value.lastError === null || typeof value.lastError === \"string\") &&\n typeof value.changedAt === \"number\";\n","// Remote-host command-channel protocol — the browser-safe contract shared by a\n// host (MulmoClaude, MulmoTerminal) and the remote/mobile client (mulmoserver).\n//\n// A host signs in to Firebase as the user, listens to that user's per-host\n// command queue in Firestore, runs a handler, and writes the result back; the\n// remote writes commands and reads results via a real-time listener. This module\n// owns the wire types + pure helpers, and must load without the Firebase SDK; the\n// Firestore path helpers live in `./server/paths.ts`. It is the single source of\n// truth so the host runner and the client never drift on the protocol.\n//\n// Ported from ../mulmoserver/src/firestore/commandChannel.ts and the per-host\n// copy that lived in MulmoClaude's server/remoteHost/. The hostId is\n// host-specific (\"mulmoclaude\", \"mulmoterminal\") and is supplied by each host.\nimport { isRecord } from \"@mulmoclaude/common\";\n\n// JSON payloads carried by the command channel. Explicit JSON types keep the\n// channel typed without resorting to any/unknown.\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\nexport type JsonObject = Record<string, JsonValue>;\n\n/** Structural JSON view of `T`, recursively.\n *\n * TypeScript gives an implicit index signature to type aliases and mapped\n * types but NOT to interfaces, so a payload assembled from domain interfaces\n * (`Shortcut`, `FeedSummary`, …) cannot satisfy `Record<string, JsonValue>`\n * structurally — even though it is plain JSON at runtime. Mapping over `T`\n * reconstructs it as an anonymous type, which does get that index signature.\n *\n * Recursive on purpose: a top-level-only map would still leave nested\n * interfaces (`{ shortcuts: Shortcut[] }`) unassignable, which is the case\n * every handler here actually has. */\n// The function branch must come BEFORE the object branch: a function IS an\n// object to TypeScript, so without it a function maps to `{}` and sails\n// through — the helper would accept a payload that serialises to nothing.\n// Verified: `toJsonObject({ callback: () => undefined })` compiled clean until\n// this branch existed (CodeRabbit, #2596).\nexport type Jsonify<T> = T extends JsonValue\n ? T\n : T extends (...args: never[]) => unknown\n ? never\n : T extends (infer U)[]\n ? Jsonify<U>[]\n : T extends object\n ? { [K in keyof T]: Jsonify<T[K]> }\n : never;\n\n/** Widen a JSON-shaped handler payload to the channel's `JsonObject`.\n *\n * Exists so the `Jsonify` reasoning above lives in ONE place. Before this,\n * eight remote-host handlers each carried their own `as unknown as JsonObject`\n * with the justification re-argued in eight slightly different comments —\n * which is how a rule stops being reviewable. */\nexport const toJsonObject = <T extends object>(payload: Jsonify<T>): JsonObject => payload as JsonObject;\n\nconst describeNonJson = (value: unknown): string => {\n if (typeof value === \"number\") return String(value);\n if (typeof value === \"object\") return \"a non-plain object\";\n return `a ${typeof value}`;\n};\n\n/** Anything carrying its own JSON form — `Date` above all — must be asked for\n * it rather than walked, because walking a `Date`'s own enumerable keys finds\n * none and flattens the timestamp to `{}`. This is the step `JSON.stringify`\n * performs before it recurses, and the channel used to get it for free. */\nconst hasToJson = (value: object): value is { toJSON: () => unknown } => \"toJSON\" in value && typeof value.toJSON === \"function\";\n\nconst jsonRepresentationOf = (value: object): unknown => (hasToJson(value) ? value.toJSON() : value);\n\n/** Rebuild `value` as JSON, or throw naming the property that cannot be. */\nfunction toJsonValue(value: unknown, path: string): JsonValue {\n if (Array.isArray(value)) return toJsonItems(value, path);\n if (isRecord(value)) {\n const represented = jsonRepresentationOf(value);\n if (represented !== value) return toJsonValue(represented, path);\n return toJsonEntries(value, path);\n }\n return toJsonScalar(value, path);\n}\n\n/** JSON's four scalar forms. Anything else — a function, a class instance, a\n * non-finite number — is what the channel cannot carry. */\nfunction toJsonScalar(value: unknown, path: string): JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n throw new Error(`${path} is ${describeNonJson(value)}, which JSON cannot represent`);\n}\n\nfunction toJsonItems(items: unknown[], path: string): JsonValue[] {\n // An absent element becomes `null`, matching `JSON.stringify` — an array has\n // to keep its length, so a hole cannot simply be dropped the way a key is.\n // `Array.from` rather than `map`, which SKIPS holes and would leave them in\n // the result: `JSON.stringify` renders a hole as null and hides that, but\n // `1 in arr` / `Object.keys` / `forEach` all still see the gap.\n return Array.from(items, (entry, index) => (entry === undefined ? null : toJsonValue(entry, `${path}[${index}]`)));\n}\n\nfunction toJsonEntries(record: Record<string, unknown>, path: string): JsonObject {\n const usable = Object.entries(record).filter(([, value]) => value !== undefined);\n return Object.fromEntries(usable.map(([key, value]) => [key, toJsonValue(value, `${path}.${key}`)]));\n}\n\n/** Runtime counterpart to `toJsonObject`, for payloads whose values are typed\n * `unknown` — a collection record, a projected view row — so no amount of\n * mapped-type work can PROVE them JSON.\n *\n * Walks the payload and rebuilds it from the values it actually inspected, so\n * the returned `JsonObject` is earned rather than asserted. Absent (`undefined`)\n * properties are dropped exactly as `JSON.stringify` drops them; anything the\n * channel could not carry — a function, a class instance, `NaN` — throws\n * naming its path, instead of reaching Firestore as a silently mangled write. */\nexport const coerceJsonObject = (payload: Record<string, unknown>): JsonObject => toJsonEntries(payload, \"payload\");\n\n// A channel routes commands to one specific host. A host's first machine uses the\n// host's fixed id (\"mulmoclaude\", \"mulmoterminal\"); a host that runs on several\n// machines gives each later one \"<id>-<8 hex>\" (RemoteHostDeps.resolveHostId), and\n// the remote finds those by listing users/{uid}/hosts.\nexport interface Channel {\n uid: string;\n hostId: string;\n}\n\nexport type CommandStatus = \"queued\" | \"processing\" | \"done\" | \"error\";\n\nexport interface CommandError {\n code: string;\n message: string;\n}\n\n// One document in a channel's commands subcollection is one API-call-like\n// request. The remote (mobile) writes method/params; the host writes\n// result/error/status.\nexport interface Command {\n method: string;\n params: JsonObject;\n status: CommandStatus;\n result: JsonValue;\n error: CommandError | null;\n createdBy: \"remote\" | \"host\";\n // Offline-queue fields (all optional; absent ⇒ pre-offline-queue behaviour, so\n // this is backward-compatible with every deployed client). Epoch-millisecond\n // NUMBERS set by the remote at enqueue time — deliberately plain numbers, not\n // Firestore Timestamps, so `isExpired` / `byCreatedAt` stay pure + browser-safe\n // and unit-testable without a Firestore fake. Clock skew over a multi-day expiry\n // window is immaterial. See plans/done/feat-remote-offline-queue.md.\n createdAt?: number; // enqueue time — age/display + best-effort dispatch bias (NOT a strict order guarantee; chat is async)\n expiresAt?: number; // deadline; past it the host deletes the command + its staged attachments\n queuedOffline?: boolean; // emitted while the host was offline (gates the remote's attachment rollback)\n}\n\n// A command is expired once `now` reaches its remote-set deadline. Absent\n// `expiresAt` ⇒ it never expires (pre-offline-queue commands). Pure with an\n// injected `now` for deterministic tests; the runner passes `Date.now()`.\nexport const isExpired = (command: Pick<Command, \"expiresAt\">, now: number): boolean => typeof command.expiresAt === \"number\" && now >= command.expiresAt;\n\n// Best-effort dispatch bias for a drained batch: oldest enqueue first. This is\n// NOT an ordering guarantee — commands run concurrently and may complete out of\n// order (chat is asynchronous, by design); it only nudges which one starts first.\n// A command with no `createdAt` sorts as oldest (0) so it is never starved.\nexport const byCreatedAt = (left: Pick<Command, \"createdAt\">, right: Pick<Command, \"createdAt\">): number => (left.createdAt ?? 0) - (right.createdAt ?? 0);\n\nexport type CommandHandler = (params: JsonObject) => JsonValue | Promise<JsonValue>;\nexport type CommandHandlers = Record<string, CommandHandler>;\n\n/** The param name a collection-serving command uses to say WHICH project's\n * collections it means. Reserved and documented now, before a phone client\n * ships, because the parts that are hard to change later are the ones being\n * written today. Four rules go with it:\n *\n * 1. **It is an OPAQUE scope, never a path.** The phone is a genuinely remote\n * client; an absolute root in a command, an artifact or a token publishes\n * the user's home directory over the wire. Mint a project id host-side and\n * resolve it host-side.\n * 2. **The phone must be able to LEARN the list.** A picker needs\n * `{ id, label }` pairs from the host — a command of its own, or a field on\n * an existing listing. Designing the scope value now is what keeps that the\n * ONLY new thing when the feature lands.\n * 3. **Handlers RESOLVE a scope; they do not hard-code one.** Write each\n * collection handler as \"read the scope from params, defaulting to the\n * host's root\" rather than calling the workspace accessor inline. Today\n * every call resolves the default and behaves exactly as it does now; the\n * day the param arrives, no handler changes.\n * 4. **The artifact stays host-built.** A remote view's srcdoc, its inlined\n * image thumbnails and its token are assembled on the host, so the phone\n * never resolves a path itself. That is what makes (1) hold without\n * trusting the client. */\nexport const COMMAND_SCOPE_PARAM = \"project\";\n\n/** Read the opaque project scope off a command's params, or `undefined` for\n * \"the host's own root\" — which is what every command means today. A\n * non-string (or empty) value is treated as absent rather than as an error: a\n * scope the host cannot resolve must fall back to the default, never to a\n * guess. Hosts pass the result to their own id → root resolver; this module\n * deliberately never sees a path. */\nexport const readCommandScope = (params: JsonObject): string | undefined => {\n const raw = params[COMMAND_SCOPE_PARAM];\n return typeof raw === \"string\" && raw.trim().length > 0 ? raw.trim() : undefined;\n};\n\n// Bumped when the command-channel wire protocol changes in a way the remote must\n// gate on. Advertised in the presence doc so the remote can check compatibility\n// before issuing commands.\n//\n// v2: offline queueing. The host honours `expiresAt` (deletes an expired command\n// + its staged attachments instead of spawning a stale chat). A remote MUST see\n// protocolVersion >= 2 before queueing a startChat while the host is offline —\n// a v1 host silently ignores `expiresAt`, so a queued chat would spawn stale on\n// reconnect with its uploads never cleaned up.\nexport const REMOTE_HOST_PROTOCOL_VERSION = 2;\n\n// The presence doc's payload: online flag + a capability advertisement. Written\n// by the host on every heartbeat; the remote reads it from the presence listener\n// it already runs (no extra round trip, known the instant the host is online).\n// Browser-safe so the mobile client compiles against the same shape.\n// `updatedAt` (a Firestore serverTimestamp) is added by the runner at write time\n// and is intentionally not part of this capability contract.\n// Which machine a presence comes from, for a host that can run on several machines\n// under one account (mulmoterminal#3092): a stable id the host recognises itself by,\n// and the name the remote shows for it.\nexport interface HostMachine {\n machineId: string;\n label: string;\n}\n\nexport interface HostPresence {\n online: boolean;\n hostId: string;\n protocolVersion: number;\n // Method names the host serves — the keys of the live handler table.\n capabilities: string[];\n machineId?: string;\n label?: string;\n}\n\n// Build the presence payload from the live handler table. Capabilities are\n// `Object.keys(handlers)` so registering a handler is the ONLY step needed to\n// advertise it — there is no second list to keep in sync.\nexport const buildHostPresence = (channel: Channel, handlers: CommandHandlers, online: boolean, machine?: HostMachine): HostPresence => ({\n online,\n hostId: channel.hostId,\n protocolVersion: REMOTE_HOST_PROTOCOL_VERSION,\n capabilities: Object.keys(handlers),\n ...(machine ? { machineId: machine.machineId, label: machine.label } : {}),\n});\n\n// Channel health as the resilient runner reports it. Browser-safe alongside the\n// wire types because the control that renders it runs in the client.\nexport { RUNNER_HEALTH_STATES, isRunnerHealth, isRunnerHealthState } from \"./health.js\";\nexport type { RunnerHealth, RunnerHealthState } from \"./health.js\";\n"],"mappings":";;AAYA,IAAa,uBAAuB;CAAC;CAAU;CAAgB;AAAS;AAWxE,IAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU;AAE9G,IAAa,uBAAuB,UAA+C,qBAAqB,MAAM,UAAU,UAAU,KAAK;;;AAIvI,IAAa,kBAAkB,UAC7B,SAAS,KAAK,KACd,oBAAoB,MAAM,KAAK,MAC9B,MAAM,cAAc,QAAQ,OAAO,MAAM,cAAc,aACxD,OAAO,MAAM,cAAc;;;;;;;;ACmB7B,IAAa,gBAAkC,YAAoC;AAEnF,IAAM,mBAAmB,UAA2B;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,KAAK,OAAO;AACrB;;;;;AAMA,IAAM,aAAa,UAAsD,YAAY,SAAS,OAAO,MAAM,WAAW;AAEtH,IAAM,wBAAwB,UAA4B,UAAU,KAAK,IAAI,MAAM,OAAO,IAAI;;AAG9F,SAAS,YAAY,OAAgB,MAAyB;CAC5D,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,YAAY,OAAO,IAAI;CACxD,IAAIA,aAAAA,SAAS,KAAK,GAAG;EACnB,MAAM,cAAc,qBAAqB,KAAK;EAC9C,IAAI,gBAAgB,OAAO,OAAO,YAAY,aAAa,IAAI;EAC/D,OAAO,cAAc,OAAO,IAAI;CAClC;CACA,OAAO,aAAa,OAAO,IAAI;AACjC;;;AAIA,SAAS,aAAa,OAAgB,MAAyB;CAC7D,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO;CACtF,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GAAG,OAAO;CAChE,MAAM,IAAI,MAAM,GAAG,KAAK,MAAM,gBAAgB,KAAK,EAAE,8BAA8B;AACrF;AAEA,SAAS,YAAY,OAAkB,MAA2B;CAMhE,OAAO,MAAM,KAAK,QAAQ,OAAO,UAAW,UAAU,KAAA,IAAY,OAAO,YAAY,OAAO,GAAG,KAAK,GAAG,MAAM,EAAE,CAAE;AACnH;AAEA,SAAS,cAAc,QAAiC,MAA0B;CAChF,MAAM,SAAS,OAAO,QAAQ,MAAM,CAAC,CAAC,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS;CAC/E,OAAO,OAAO,YAAY,OAAO,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,YAAY,OAAO,GAAG,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC;AACrG;;;;;;;;;;AAWA,IAAa,oBAAoB,YAAiD,cAAc,SAAS,SAAS;AA0ClH,IAAa,aAAa,SAAqC,QAAyB,OAAO,QAAQ,cAAc,YAAY,OAAO,QAAQ;AAMhJ,IAAa,eAAe,MAAkC,WAA+C,KAAK,aAAa,MAAM,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;AA2BxJ,IAAa,sBAAsB;;;;;;;AAQnC,IAAa,oBAAoB,WAA2C;CAC1E,MAAM,MAAM,OAAO;CACnB,OAAO,OAAO,QAAQ,YAAY,IAAI,KAAK,CAAC,CAAC,SAAS,IAAI,IAAI,KAAK,IAAI,KAAA;AACzE;AAWA,IAAa,+BAA+B;AA6B5C,IAAa,qBAAqB,SAAkB,UAA2B,QAAiB,aAAyC;CACvI;CACA,QAAQ,QAAQ;CAChB,iBAAA;CACA,cAAc,OAAO,KAAK,QAAQ;CAClC,GAAI,UAAU;EAAE,WAAW,QAAQ;EAAW,OAAO,QAAQ;CAAM,IAAI,CAAC;AAC1E"}
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_dist = require("../dist-CdSEjlVx.cjs");
2
+ const require_dist = require("../dist--k7dcIzm.cjs");
3
3
  const require_project = require("../project-DDTIVEMU.cjs");
4
4
  // src/remote-view/index.ts
5
5
  /** Bump when the bootstrap/message contract changes shape; the bootstrap
@@ -1,4 +1,4 @@
1
- import { c as isRecord } from "../dist--searOB5.js";
1
+ import { c as isRecord } from "../dist-Cb-KNFRA.js";
2
2
  import { n as projectRecordFields } from "../project-mU6-xLfy.js";
3
3
  // src/remote-view/index.ts
4
4
  /** Bump when the bootstrap/message contract changes shape; the bootstrap
@@ -17,3 +17,9 @@ export declare function isCacheValid(cachePath: string): boolean;
17
17
  * marker is written ONLY after tar exits 0 — readers should test
18
18
  * `isCacheValid()`, not `existsSync(cachePath)`. */
19
19
  export declare function extractTgz(tgzAbs: string, destDir: string): void;
20
+ export declare function publishStaged(staging: string, destDir: string): void;
21
+ /** Unpack `bytes` (a gzipped npm tarball) to `destDir` so that no reader ever sees a partial tree, even
22
+ * with two processes (MulmoClaude and MulmoTerminal on one workspace) unpacking the same folder at once:
23
+ * into a unique sibling folder, completed with the marker, then renamed into place. The bytes are the
24
+ * ones the caller already read and keyed the folder by, so what is unpacked is what the key names. */
25
+ export declare function extractBytesAtomically(bytes: Buffer, destDir: string): void;
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("../rolldown-runtime-CmQyd0Gu.cjs");
3
- const require_dist = require("../dist-CdSEjlVx.cjs");
3
+ const require_dist = require("../dist--k7dcIzm.cjs");
4
4
  const require_containment = require("../containment-Dc3gO4wD.cjs");
5
5
  const require_json = require("../json-BGdV2cz6.cjs");
6
6
  const require_atomic = require("../atomic-cqafMWEI.cjs");
@@ -142,6 +142,53 @@ function extractTgz(tgzAbs, destDir) {
142
142
  throw err;
143
143
  }
144
144
  }
145
+ var removeQuietly = (dir) => {
146
+ try {
147
+ (0, node_fs.rmSync)(dir, {
148
+ recursive: true,
149
+ force: true
150
+ });
151
+ } catch {}
152
+ };
153
+ function publishStaged(staging, destDir) {
154
+ try {
155
+ (0, node_fs.renameSync)(staging, destDir);
156
+ } catch (err) {
157
+ removeQuietly(staging);
158
+ if (!isCacheValid(destDir)) throw err;
159
+ }
160
+ }
161
+ /** Unpack `bytes` (a gzipped npm tarball) to `destDir` so that no reader ever sees a partial tree, even
162
+ * with two processes (MulmoClaude and MulmoTerminal on one workspace) unpacking the same folder at once:
163
+ * into a unique sibling folder, completed with the marker, then renamed into place. The bytes are the
164
+ * ones the caller already read and keyed the folder by, so what is unpacked is what the key names. */
165
+ function extractBytesAtomically(bytes, destDir) {
166
+ if (isCacheValid(destDir)) return;
167
+ const parent = node_path.default.dirname(destDir);
168
+ (0, node_fs.mkdirSync)(parent, { recursive: true });
169
+ const staging = (0, node_fs.mkdtempSync)(node_path.default.join(parent, `.${node_path.default.basename(destDir)}-`));
170
+ try {
171
+ (0, node_child_process.execFileSync)("tar", [
172
+ "-xzf",
173
+ "-",
174
+ "-C",
175
+ staging,
176
+ "--strip-components=1"
177
+ ], {
178
+ input: bytes,
179
+ stdio: [
180
+ "pipe",
181
+ "pipe",
182
+ "pipe"
183
+ ]
184
+ });
185
+ writeMarker(node_path.default.join(staging, EXTRACT_MARKER));
186
+ publishStaged(staging, destDir);
187
+ } catch (err) {
188
+ removeQuietly(staging);
189
+ throw err;
190
+ }
191
+ }
145
192
  // src/runtime-plugins/containment.ts
146
193
  /** True when `file` exists and, with every link followed, is inside `root`. */
147
194
  function resolvesInside(file, root) {
@@ -313,9 +360,50 @@ function ensureInsideBase(candidate, base) {
313
360
  /** Make a ledger entry's cache directory ready to load: both of its paths anchored inside their
314
361
  * roots, its tgz present, and the tgz extracted unless a complete extract is already there.
315
362
  * Returns the cache directory, or null (logged) when the entry cannot be loaded. */
363
+ var MAX_PACKAGE_FILE_BYTES = 52428800;
364
+ var READ_CHUNK_BYTES$1 = 65536;
365
+ var READ_FLAGS$1 = node_fs.constants.O_RDONLY | (node_fs.constants.O_NONBLOCK ?? 0);
366
+ function readChunks(fileHandle, maxBytes) {
367
+ const chunks = [];
368
+ let received = 0;
369
+ for (;;) {
370
+ const chunk = Buffer.alloc(READ_CHUNK_BYTES$1);
371
+ const bytesRead = (0, node_fs.readSync)(fileHandle, chunk, 0, READ_CHUNK_BYTES$1, null);
372
+ if (bytesRead === 0) return Buffer.concat(chunks, received);
373
+ received += bytesRead;
374
+ if (received > maxBytes) return null;
375
+ chunks.push(chunk.subarray(0, bytesRead));
376
+ }
377
+ }
378
+ /** The package file's bytes, or null when it is not a regular file or grows past the limit while read. */
379
+ function readPackageFile$1(tgzAbs) {
380
+ const fileHandle = (0, node_fs.openSync)(tgzAbs, READ_FLAGS$1);
381
+ try {
382
+ return (0, node_fs.fstatSync)(fileHandle).isFile() ? readChunks(fileHandle, MAX_PACKAGE_FILE_BYTES) : null;
383
+ } finally {
384
+ (0, node_fs.closeSync)(fileHandle);
385
+ }
386
+ }
387
+ function loggedPackageBytes(tgzAbs, entry, log) {
388
+ try {
389
+ const bytes = readPackageFile$1(tgzAbs);
390
+ if (bytes === null) log.warn("tgz is not a package file within the size limit — skipping", {
391
+ name: entry.name,
392
+ tgz: entry.tgz
393
+ });
394
+ return bytes;
395
+ } catch (err) {
396
+ log.error("tgz unreadable — skipping", {
397
+ name: entry.name,
398
+ tgz: entry.tgz,
399
+ error: String(err)
400
+ });
401
+ return null;
402
+ }
403
+ }
316
404
  function prepareLedgerEntry(entry, roots, log) {
317
405
  const tgzAbs = node_path.default.join(roots.pluginsDir, entry.tgz);
318
- const cachePath = node_path.default.join(roots.cacheDir, entry.name, entry.version);
406
+ const versionDir = node_path.default.join(roots.cacheDir, entry.name, entry.version);
319
407
  if (!ensureInsideBase(tgzAbs, roots.pluginsDir)) {
320
408
  log.warn("ledger entry tgz escapes plugins root — skipping", {
321
409
  name: entry.name,
@@ -323,7 +411,7 @@ function prepareLedgerEntry(entry, roots, log) {
323
411
  });
324
412
  return null;
325
413
  }
326
- if (!ensureInsideBase(cachePath, roots.cacheDir)) {
414
+ if (!ensureInsideBase(versionDir, roots.cacheDir)) {
327
415
  log.warn("ledger entry escapes plugin cache root — skipping", {
328
416
  name: entry.name,
329
417
  version: entry.version
@@ -337,8 +425,11 @@ function prepareLedgerEntry(entry, roots, log) {
337
425
  });
338
426
  return null;
339
427
  }
428
+ const bytes = loggedPackageBytes(tgzAbs, entry, log);
429
+ if (bytes === null) return null;
430
+ const cachePath = node_path.default.join(versionDir, (0, node_crypto.createHash)("sha256").update(bytes).digest("hex"));
340
431
  if (!isCacheValid(cachePath)) try {
341
- extractTgz(tgzAbs, cachePath);
432
+ extractBytesAtomically(bytes, cachePath);
342
433
  log.info("extracted", {
343
434
  name: entry.name,
344
435
  version: entry.version
@@ -1001,16 +1092,6 @@ async function preparePlan(source, deps) {
1001
1092
  raw: ledger.raw
1002
1093
  };
1003
1094
  }
1004
- async function dropStaleCache(plan, raw, paths) {
1005
- const sameVersion = parseLedger(raw).filter((entry) => entry.name === plan.name && entry.version === plan.version);
1006
- if (sameVersion.length > 0 && sameVersion.every((entry) => entry.tgz === plan.tgz)) return;
1007
- const cacheDir = paths.cacheDir ?? node_path.default.join(paths.pluginsDir, ".cache");
1008
- const stale = node_path.default.join(cacheDir, plan.name, plan.version);
1009
- if (ensureInsideBase(stale, cacheDir)) await (0, node_fs_promises.rm)(stale, {
1010
- recursive: true,
1011
- force: true
1012
- });
1013
- }
1014
1095
  async function writePackageFile(plan, bytes, pluginsDir) {
1015
1096
  const tgzPath = node_path.default.join(pluginsDir, plan.tgz);
1016
1097
  const fileWasThere = (0, node_fs.existsSync)(tgzPath);
@@ -1032,7 +1113,6 @@ async function commit(plan, bytes, raw, deps) {
1032
1113
  source: plan.source
1033
1114
  };
1034
1115
  try {
1035
- await dropStaleCache(plan, raw, deps.paths);
1036
1116
  await writeLedger(deps.paths.ledgerPath, withLedgerEntry(raw, entry));
1037
1117
  } catch (err) {
1038
1118
  if (!fileWasThere) await (0, node_fs_promises.rm)(tgzPath, { force: true });