inplan 0.1.25 → 0.1.27

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.
@@ -400,32 +400,42 @@ async function fetchAndCache(bundleUrl, leaseToken, opts) {
400
400
  fs.writeFileSync(path.join(opts.cacheDir, "current.txt"), manifest.version);
401
401
  return manifest.version;
402
402
  }
403
- async function resolveDesktopPlugin(options) {
403
+ async function resolvePluginOutcome(options) {
404
404
  const publicKey = options.publicKey ?? PLUGIN_PUBLIC_KEY;
405
405
  const now = options.now ?? Date.now();
406
406
  const fetchImpl = options.fetchImpl ?? fetch;
407
- if (!publicKey) return null;
407
+ const cached = () => {
408
+ try {
409
+ const current = fs.readFileSync(path.join(options.cacheDir, "current.txt"), "utf8").trim();
410
+ const plugin = current ? loadCached(options.cacheDir, current, publicKey, now) : null;
411
+ return plugin ? { plugin, reason: null } : { plugin: null, reason: "unavailable" };
412
+ } catch {
413
+ return { plugin: null, reason: "unavailable" };
414
+ }
415
+ };
416
+ if (!publicKey) return { plugin: null, reason: "unavailable" };
408
417
  if (options.token) {
409
418
  try {
410
419
  const res = await fetchImpl(`${base(options.apiBase)}api/v1/desktop-plugin`, { headers: { authorization: `Bearer ${options.token}` } });
411
420
  if (res.ok) {
412
421
  const grant = await res.json();
413
- if (grant.entitled === false) return null;
422
+ if (grant.entitled === false) return { plugin: null, reason: "unentitled" };
414
423
  if (grant.entitled && grant.lease && grant.bundleUrl) {
415
- if (!verifyLease(grant.lease, publicKey, now)) return null;
424
+ if (!verifyLease(grant.lease, publicKey, now)) return { plugin: null, reason: "unavailable" };
416
425
  const version = await fetchAndCache(grant.bundleUrl, grant.lease, { cacheDir: options.cacheDir, publicKey, fetchImpl });
417
- if (version) return loadCached(options.cacheDir, version, publicKey, now);
426
+ if (version) {
427
+ const plugin = loadCached(options.cacheDir, version, publicKey, now);
428
+ if (plugin) return { plugin, reason: null };
429
+ }
418
430
  }
419
431
  }
420
432
  } catch {
421
433
  }
422
434
  }
423
- try {
424
- const current = fs.readFileSync(path.join(options.cacheDir, "current.txt"), "utf8").trim();
425
- return current ? loadCached(options.cacheDir, current, publicKey, now) : null;
426
- } catch {
427
- return null;
428
- }
435
+ return cached();
436
+ }
437
+ async function resolveDesktopPlugin(options) {
438
+ return (await resolvePluginOutcome(options)).plugin;
429
439
  }
430
440
  const MAX_BACKUPS = 25;
431
441
  class Session {
@@ -134,6 +134,12 @@ body {
134
134
  .ap-agent-dot { width: 10px; height: 10px; border-radius: 50%; flex: 0 0 auto; }
135
135
  .ap-agent-local { background: #2bb673; } /* agent on your machine */
136
136
  .ap-agent-off { background: var(--danger); } /* no agent connected */
137
+ /* Agent holds the turn. A turn-based local agent drops its presence socket while it works, so this
138
+ covers the window where "no peer" means "busy", not "gone" — amber, and pulsing so it reads as
139
+ activity rather than a warning. */
140
+ .ap-agent-working { background: #e0a23b; animation: ap-agent-pulse 1.6s ease-in-out infinite; }
141
+ @keyframes ap-agent-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.45; } }
142
+ @media (prefers-reduced-motion: reduce) { .ap-agent-working { animation: none; } }
137
143
  .ap-agent-pie { position: relative; width: 14px; height: 14px; border-radius: 50%; flex: 0 0 auto; }
138
144
  /* Green "connected" core; only the thin outer band of .ap-agent-pie shows the usage conic. The
139
145
  1px box-shadow ring is the button's background colour, leaving a 1px gap between the core and the
@@ -162,6 +168,10 @@ body {
162
168
  .ap-agent-localcmd-msg { flex: 1; min-width: 0; font-size: 11px; line-height: 1.45; background: var(--paper); border: 1px solid var(--line); border-radius: 6px; padding: 5px 7px; color: var(--fg); user-select: text; -webkit-user-select: text; }
163
169
  .ap-agent-localcmd-copy { flex: 0 0 auto; border: 1px solid var(--line-strong); background: var(--bg); border-radius: 6px; padding: 0 9px; font: inherit; font-size: 11px; cursor: pointer; color: var(--fg); }
164
170
  .ap-agent-localcmd-copy:hover { background: var(--accent-soft); }
171
+ /* Same slot as the connect command, when the plan doesn't include a local agent here. */
172
+ .ap-agent-upsell .ap-agent-localcmd-hint { color: var(--fg); line-height: 1.45; }
173
+ .ap-agent-upgrade { width: 100%; border: 1px solid var(--accent); background: var(--accent); color: #fbfaf6; border-radius: 6px; padding: 5px 9px; font: inherit; font-size: 11px; cursor: pointer; }
174
+ .ap-agent-upgrade:hover { filter: brightness(1.06); }
165
175
 
166
176
  .ap-topbar button, .ap-tabs button { font: inherit; }
167
177
  .ap-topbar > button { border: 1px solid var(--line-strong); background: var(--bg); border-radius: 7px; padding: 4px 12px; cursor: pointer; color: var(--fg); }
@@ -43594,12 +43594,15 @@ var EN = {
43594
43594
  "agent.dontConnect": "Don't auto-connect",
43595
43595
  "agent.remote": "remote",
43596
43596
  "agent.local": "local",
43597
+ "agent.working": "working",
43597
43598
  "agent.disconnected": "disconnected",
43598
43599
  "agent.title": "Agent: {label}",
43599
43600
  "agent.connectionLabel": "Agent connection — {label}",
43600
43601
  "agent.whereCloud": "cloud",
43601
43602
  "agent.whereLocal": "your machine",
43602
43603
  "agent.detail": "Agent · {where}",
43604
+ // Busy but with no presence peer, so we can't say where it runs — deliberately location-free.
43605
+ "agent.workingNoWhere": "Agent · working",
43603
43606
  "agent.none": "No agent connected",
43604
43607
  "agent.plan": "Plan {pct}%",
43605
43608
  "agent.overIncluded": "— over included",
@@ -43608,7 +43611,12 @@ var EN = {
43608
43611
  "agent.atLimit": "Usage limit reached — turns are paused until your plan resets or you upgrade",
43609
43612
  "agent.connection": "Agent connection",
43610
43613
  "agent.localCmdHint": "Paste this to your coding agent:",
43611
- "agent.localCmdBody": "Collaborate with me on my inplan plan. Check the CLI with `inplan --version` (if missing, install it: `npm i -g inplan`), sign in with `inplan login`, then run `{cmd}` and work with me through the comments.",
43614
+ // Installs unconditionally rather than only when the CLI is missing: an out-of-date CLI attaches
43615
+ // to a cloud doc and behaves plausibly while lacking the code path the document needs, so
43616
+ // "install it if missing" left the one failure mode that has no symptom.
43617
+ "agent.localCmdBody": "Collaborate with me on my inplan plan. Install or update the CLI with `npm i -g inplan@latest`, sign in with `inplan login` if you haven't yet, then run `{cmd}` and work with me through the comments.",
43618
+ "agent.localLocked": "Connecting your own agent to a cloud document is on Pro and above.",
43619
+ "agent.seePlans": "See plans",
43612
43620
  "agent.copy": "Copy",
43613
43621
  "agent.copied": "Copied",
43614
43622
  // comment rail
@@ -44942,17 +44950,21 @@ function QuotaPie({ pct, color }) {
44942
44950
  }
44943
44951
  function AgentIndicator({
44944
44952
  location,
44953
+ working,
44945
44954
  model,
44946
44955
  quota,
44947
44956
  byoKey,
44948
44957
  policy,
44949
44958
  onSetPolicy,
44959
+ localEntitled,
44960
+ onUpgrade,
44950
44961
  localCommand
44951
44962
  }) {
44952
44963
  const t2 = useT();
44953
44964
  const [open, setOpen] = reactExports.useState(false);
44954
44965
  const [copied, setCopied] = reactExports.useState(false);
44955
44966
  const ref = reactExports.useRef(null);
44967
+ const localGated = localEntitled === false;
44956
44968
  const agentMessage = localCommand ? t2("agent.localCmdBody", { cmd: localCommand }) : "";
44957
44969
  const preview = agentMessage.length > 84 ? `${agentMessage.slice(0, 52)} … ${agentMessage.slice(-26)}` : agentMessage;
44958
44970
  const copy = () => {
@@ -44974,9 +44986,10 @@ function AgentIndicator({
44974
44986
  { value: "manual", label: t2("agent.dontConnect") }
44975
44987
  ];
44976
44988
  const labelFor = (loc, m2) => {
44977
- if (loc === "cloud") return `${t2("agent.remote")}${m2 ? ` (${m2})` : ""}`;
44978
- if (loc === "local") return `${t2("agent.local")}${m2 ? ` (${m2})` : ""}`;
44979
- return t2("agent.disconnected");
44989
+ const suffix = `${m2 ? ` (${m2})` : ""}${working ? ` · ${t2("agent.working")}` : ""}`;
44990
+ if (loc === "cloud") return `${t2("agent.remote")}${suffix}`;
44991
+ if (loc === "local") return `${t2("agent.local")}${suffix}`;
44992
+ return working ? `${t2("agent.working")}` : t2("agent.disconnected");
44980
44993
  };
44981
44994
  reactExports.useEffect(() => {
44982
44995
  const onDown = (e) => {
@@ -44990,7 +45003,9 @@ function AgentIndicator({
44990
45003
  const color = byoKey ? "var(--agent-byo, #1e3a8a)" : quota ? quota.overage || quota.usedPct >= 0.95 ? "#c0392b" : quota.usedPct >= 0.75 ? "#e0a23b" : "#3fa46a" : "var(--accent)";
44991
45004
  icon = quota ? /* @__PURE__ */ jsxRuntimeExports.jsx(QuotaPie, { pct: quota.usedPct, color }) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ap-agent-dot", style: { background: color }, "aria-hidden": "true" });
44992
45005
  } else if (location === "local") {
44993
- icon = /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ap-agent-dot ap-agent-local", "aria-hidden": "true" });
45006
+ icon = /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `ap-agent-dot ap-agent-local${working ? " ap-agent-working" : ""}`, "aria-hidden": "true" });
45007
+ } else if (working) {
45008
+ icon = /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ap-agent-dot ap-agent-working", "aria-hidden": "true" });
44994
45009
  } else {
44995
45010
  icon = /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "ap-agent-dot ap-agent-off", "aria-hidden": "true" });
44996
45011
  }
@@ -45004,7 +45019,12 @@ function AgentIndicator({
45004
45019
  ] }),
45005
45020
  open && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "ap-agent-menu", role: "menu", children: [
45006
45021
  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "ap-agent-detail", children: [
45007
- location ? `${t2("agent.detail", { where: location === "cloud" ? t2("agent.whereCloud") : t2("agent.whereLocal") })}${model ? ` · ${model}` : ""}` : t2("agent.none"),
45022
+ location ? `${t2("agent.detail", { where: location === "cloud" ? t2("agent.whereCloud") : t2("agent.whereLocal") })}${model ? ` · ${model}` : ""}${working ? ` · ${t2("agent.working")}` : ""}` : (
45023
+ // Busy with no peer: report the state WITHOUT claiming where it runs. `working` carries
45024
+ // no location, and inferring "your machine" would only be right because a local CLI
45025
+ // happens to be the one agent shaped this way today.
45026
+ working ? `${t2("agent.workingNoWhere")}` : t2("agent.none")
45027
+ ),
45008
45028
  quota && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ap-agent-quota", children: `${t2("agent.plan", { pct: Math.round(quota.usedPct * 100) })}${quota.overage ? ` ${t2("agent.overIncluded")}` : ""}` }),
45009
45029
  quotaWarn && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `ap-agent-quota-warn ap-agent-quota-${quotaWarn}`, role: "status", children: t2(quotaWarn === "at" ? "agent.atLimit" : "agent.nearLimit") })
45010
45030
  ] }),
@@ -45022,7 +45042,11 @@ function AgentIndicator({
45022
45042
  },
45023
45043
  o.value
45024
45044
  )) }),
45025
- policy === "local" && agentMessage && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "ap-agent-localcmd", children: [
45045
+ policy === "local" && localGated && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "ap-agent-localcmd ap-agent-upsell", children: [
45046
+ /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ap-agent-localcmd-hint", children: t2("agent.localLocked") }),
45047
+ onUpgrade && /* @__PURE__ */ jsxRuntimeExports.jsx("button", { className: "ap-agent-upgrade", onClick: () => void onUpgrade(), children: t2("agent.seePlans") })
45048
+ ] }),
45049
+ policy === "local" && !localGated && agentMessage && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "ap-agent-localcmd", children: [
45026
45050
  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ap-agent-localcmd-hint", children: t2("agent.localCmdHint") }),
45027
45051
  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "ap-agent-localcmd-row", children: [
45028
45052
  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ap-agent-localcmd-msg", title: agentMessage, children: preview }),
@@ -45876,7 +45900,7 @@ function App(props = {}) {
45876
45900
  document.addEventListener("keydown", onKey);
45877
45901
  return () => document.removeEventListener("keydown", onKey);
45878
45902
  }, [composer, findOpen, proposal, reviewOpen, undo2, redo2, readOnly2]);
45879
- const agentLocked = mode.locksEditor && agentThinking;
45903
+ const agentLocked = agentThinking;
45880
45904
  const editingLocked = agentLocked || readOnly2;
45881
45905
  const takeBackControl = reactExports.useCallback(() => {
45882
45906
  setAgentThinking(false);
@@ -46622,6 +46646,7 @@ function App(props = {}) {
46622
46646
  } : void 0,
46623
46647
  forceSettingsOpen,
46624
46648
  locked: editingLocked,
46649
+ agentThinking,
46625
46650
  nav: typeof hostApi().navigate === "function" ? { canBack: navState.canBack, canForward: navState.canForward, onBack: () => void hostApi().navigate?.("back"), onForward: () => void hostApi().navigate?.("forward") } : void 0
46626
46651
  }
46627
46652
  ),
@@ -47108,7 +47133,7 @@ function TopBar(props) {
47108
47133
  const { cadence, acceptance, panes, onMode } = props;
47109
47134
  const profile = useProfile();
47110
47135
  const t2 = useT();
47111
- const noAgent = profile?.presenceAware === true && profile.agentAvailable !== true && profile.agentLocation == null;
47136
+ const noAgent = profile?.presenceAware === true && profile.agentAvailable !== true && profile.agentLocation == null && props.agentThinking !== true;
47112
47137
  const noAgentTitle = noAgent ? t2("topbar.noAgent") : void 0;
47113
47138
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("header", { className: "ap-topbar", children: [
47114
47139
  props.onBack && /* @__PURE__ */ jsxRuntimeExports.jsxs("button", { className: "ap-iconbtn ap-iconbtn--primary", onClick: props.onBack, title: t2("topbar.back"), "aria-label": t2("topbar.back"), children: [
@@ -47186,11 +47211,14 @@ function TopBar(props) {
47186
47211
  AgentIndicator,
47187
47212
  {
47188
47213
  location: profile.agentLocation,
47214
+ working: props.agentThinking === true,
47189
47215
  model: profile.agentModel,
47190
47216
  quota: profile.agentQuota,
47191
47217
  byoKey: profile.agentByoKey,
47192
47218
  policy: profile.agentPolicy,
47193
47219
  onSetPolicy: profile.onSetAgentPolicy,
47220
+ localEntitled: profile.agentLocalEntitled,
47221
+ onUpgrade: profile.onUpgrade,
47194
47222
  localCommand: hostApi().localAgentCommand
47195
47223
  }
47196
47224
  ),
@@ -21,8 +21,8 @@
21
21
  content="default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' inplan-plugin:; img-src 'self' file: https:; connect-src 'self' inplan-plugin: ws://127.0.0.1:* ws://localhost:*; frame-src https://inplan.ai http://127.0.0.1:* http://localhost:*"
22
22
  />
23
23
  <title>inplan</title>
24
- <script type="module" crossorigin src="./assets/index-K0WqENF0.js"></script>
25
- <link rel="stylesheet" crossorigin href="./assets/index-i6zzDOQL.css">
24
+ <script type="module" crossorigin src="./assets/index-CLk_2VIF.js"></script>
25
+ <link rel="stylesheet" crossorigin href="./assets/index-BsT_GmrR.css">
26
26
  </head>
27
27
  <body>
28
28
  <div id="root"></div>
package/bin/cli.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import { execFileSync as execFileSync2, spawn as spawn3, spawnSync } from "child_process";
5
5
  import { createHash as createHash4 } from "crypto";
6
6
  import { createRequire } from "module";
7
- import { appendFileSync as appendFileSync2, copyFileSync, existsSync as existsSync9, mkdirSync as mkdirSync8, readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync, renameSync, statSync as statSync2, writeFileSync as writeFileSync8 } from "fs";
7
+ import { appendFileSync as appendFileSync2, copyFileSync, existsSync as existsSync9, mkdirSync as mkdirSync8, readdirSync as readdirSync2, readFileSync as readFileSync9, realpathSync, renameSync as renameSync2, rmSync as rmSync2, statSync as statSync3, writeFileSync as writeFileSync8 } from "fs";
8
8
  import { homedir as homedir6 } from "os";
9
9
  import { basename as basename3, dirname as dirname9, isAbsolute as isAbsolute2, join as join9, relative as relative4, resolve as resolve3 } from "path";
10
10
  import { fileURLToPath as fileURLToPath2, pathToFileURL as pathToFileURL2 } from "url";
@@ -589,32 +589,39 @@ async function fetchAndCache(bundleUrl, leaseToken, opts) {
589
589
  writeFileSync5(join5(opts.cacheDir, "current.txt"), manifest.version);
590
590
  return manifest.version;
591
591
  }
592
- async function resolveDesktopPlugin(options) {
592
+ async function resolvePluginOutcome(options) {
593
593
  const publicKey = options.publicKey ?? PLUGIN_PUBLIC_KEY;
594
594
  const now = options.now ?? Date.now();
595
595
  const fetchImpl = options.fetchImpl ?? fetch;
596
- if (!publicKey) return null;
596
+ const cached = () => {
597
+ try {
598
+ const current = readFileSync6(join5(options.cacheDir, "current.txt"), "utf8").trim();
599
+ const plugin = current ? loadCached(options.cacheDir, current, publicKey, now) : null;
600
+ return plugin ? { plugin, reason: null } : { plugin: null, reason: "unavailable" };
601
+ } catch {
602
+ return { plugin: null, reason: "unavailable" };
603
+ }
604
+ };
605
+ if (!publicKey) return { plugin: null, reason: "unavailable" };
597
606
  if (options.token) {
598
607
  try {
599
608
  const res = await fetchImpl(`${base(options.apiBase)}api/v1/desktop-plugin`, { headers: { authorization: `Bearer ${options.token}` } });
600
609
  if (res.ok) {
601
610
  const grant = await res.json();
602
- if (grant.entitled === false) return null;
611
+ if (grant.entitled === false) return { plugin: null, reason: "unentitled" };
603
612
  if (grant.entitled && grant.lease && grant.bundleUrl) {
604
- if (!verifyLease(grant.lease, publicKey, now)) return null;
613
+ if (!verifyLease(grant.lease, publicKey, now)) return { plugin: null, reason: "unavailable" };
605
614
  const version = await fetchAndCache(grant.bundleUrl, grant.lease, { cacheDir: options.cacheDir, publicKey, fetchImpl });
606
- if (version) return loadCached(options.cacheDir, version, publicKey, now);
615
+ if (version) {
616
+ const plugin = loadCached(options.cacheDir, version, publicKey, now);
617
+ if (plugin) return { plugin, reason: null };
618
+ }
607
619
  }
608
620
  }
609
621
  } catch {
610
622
  }
611
623
  }
612
- try {
613
- const current = readFileSync6(join5(options.cacheDir, "current.txt"), "utf8").trim();
614
- return current ? loadCached(options.cacheDir, current, publicKey, now) : null;
615
- } catch {
616
- return null;
617
- }
624
+ return cached();
618
625
  }
619
626
 
620
627
  // src/agentAuthor.ts
@@ -669,7 +676,7 @@ function gitIdentity(dir, run = defaultRun) {
669
676
  }
670
677
 
671
678
  // src/cliAuth.ts
672
- import { chmodSync, existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync4, rmSync, writeFileSync as writeFileSync3 } from "fs";
679
+ import { chmodSync, existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync, rmSync, statSync as statSync2, utimesSync, writeFileSync as writeFileSync3 } from "fs";
673
680
  import { homedir as homedir3 } from "os";
674
681
  import { dirname as dirname5, join as join4 } from "path";
675
682
  import { createClient as createClient2 } from "@supabase/supabase-js";
@@ -824,7 +831,14 @@ function loadAuth() {
824
831
  try {
825
832
  const raw = JSON.parse(readFileSync4(path, "utf8"));
826
833
  if (typeof raw.url === "string" && typeof raw.anonKey === "string" && typeof raw.refreshToken === "string") {
827
- return { url: raw.url, anonKey: raw.anonKey, refreshToken: raw.refreshToken, ...raw.email ? { email: raw.email } : {} };
834
+ return {
835
+ url: raw.url,
836
+ anonKey: raw.anonKey,
837
+ refreshToken: raw.refreshToken,
838
+ ...raw.email ? { email: raw.email } : {},
839
+ ...typeof raw.accessToken === "string" ? { accessToken: raw.accessToken } : {},
840
+ ...typeof raw.expiresAt === "number" ? { expiresAt: raw.expiresAt } : {}
841
+ };
828
842
  }
829
843
  return null;
830
844
  } catch {
@@ -834,32 +848,125 @@ function loadAuth() {
834
848
  function saveAuth(auth) {
835
849
  const path = authPath();
836
850
  mkdirSync3(dirname5(path), { recursive: true });
837
- writeFileSync3(path, `${JSON.stringify(auth, null, 2)}
851
+ const tmp = `${path}.${process.pid}.tmp`;
852
+ writeFileSync3(tmp, `${JSON.stringify(auth, null, 2)}
838
853
  `, { mode: 384 });
839
854
  try {
840
- chmodSync(path, 384);
855
+ chmodSync(tmp, 384);
841
856
  } catch {
842
857
  }
858
+ renameSync(tmp, path);
843
859
  }
844
860
  function clearAuth() {
845
861
  const path = authPath();
846
862
  if (existsSync5(path)) rmSync(path, { force: true });
847
863
  }
848
- async function authedSession() {
849
- const auth = loadAuth();
850
- if (!auth) return null;
851
- const db = createClient2(auth.url, auth.anonKey, {
852
- auth: { persistSession: false, autoRefreshToken: true, detectSessionInUrl: false },
864
+ var LOCK_WAIT_MS = 1e4;
865
+ var LOCK_STALE_MS = 6e4;
866
+ function lockDir() {
867
+ return join4(process.env.INPLAN_HOME || join4(homedir3(), ".inplan"), "auth.lock");
868
+ }
869
+ function lockOwnerPath() {
870
+ return join4(lockDir(), "owner");
871
+ }
872
+ async function withAuthLock(fn, opts = {}) {
873
+ const lock = lockDir();
874
+ mkdirSync3(process.env.INPLAN_HOME || join4(homedir3(), ".inplan"), { recursive: true });
875
+ const token = `${process.pid}-${Date.now()}-${Math.floor(Math.random() * 1e9)}`;
876
+ const waitMs = opts.waitMs ?? LOCK_WAIT_MS;
877
+ const staleMs = opts.staleMs ?? LOCK_STALE_MS;
878
+ const deadline = Date.now() + waitMs;
879
+ let held = false;
880
+ while (Date.now() < deadline) {
881
+ try {
882
+ mkdirSync3(lock);
883
+ writeFileSync3(lockOwnerPath(), token);
884
+ held = true;
885
+ break;
886
+ } catch (e) {
887
+ if (e.code !== "EEXIST") throw e;
888
+ try {
889
+ if (Date.now() - statSync2(lock).mtimeMs > staleMs) {
890
+ const aside = `${lock}.stale-${token}`;
891
+ renameSync(lock, aside);
892
+ rmSync(aside, { recursive: true, force: true });
893
+ continue;
894
+ }
895
+ } catch {
896
+ continue;
897
+ }
898
+ await new Promise((r) => setTimeout(r, 40 + Math.floor(Math.random() * 40)));
899
+ }
900
+ }
901
+ if (!held) return { acquired: false };
902
+ const stillMine = () => {
903
+ try {
904
+ return readFileSync4(lockOwnerPath(), "utf8") === token;
905
+ } catch {
906
+ return false;
907
+ }
908
+ };
909
+ const beat = setInterval(() => {
910
+ try {
911
+ if (stillMine()) utimesSync(lock, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date());
912
+ } catch {
913
+ }
914
+ }, Math.max(1, Math.floor(staleMs / 3)));
915
+ if (typeof beat.unref === "function") beat.unref();
916
+ try {
917
+ return { acquired: true, value: await fn({ stillMine }) };
918
+ } finally {
919
+ clearInterval(beat);
920
+ try {
921
+ if (readFileSync4(lockOwnerPath(), "utf8") === token) rmSync(lock, { recursive: true, force: true });
922
+ } catch {
923
+ }
924
+ }
925
+ }
926
+ var ACCESS_SKEW_S = 120;
927
+ function newClient(auth) {
928
+ return createClient2(auth.url, auth.anonKey, {
929
+ auth: { persistSession: false, autoRefreshToken: false, detectSessionInUrl: false },
853
930
  realtime: realtimeTransport
854
931
  });
855
- const { data, error } = await db.auth.refreshSession({ refresh_token: auth.refreshToken });
856
- if (error || !data.session) return null;
857
- const rotated = data.session.refresh_token || auth.refreshToken;
858
- const email = data.session.user?.email ?? auth.email;
859
- if (rotated !== auth.refreshToken || email !== auth.email) {
860
- saveAuth({ ...auth, refreshToken: rotated, ...email ? { email } : {} });
861
- }
862
- return { db, session: data.session };
932
+ }
933
+ async function reuseCached(auth, skewS = ACCESS_SKEW_S) {
934
+ if (!auth.accessToken || !auth.expiresAt) return null;
935
+ if (auth.expiresAt - Math.floor(Date.now() / 1e3) <= skewS) return null;
936
+ const db = newClient(auth);
937
+ const { data, error } = await db.auth.setSession({ access_token: auth.accessToken, refresh_token: auth.refreshToken });
938
+ return error || !data.session ? null : { db, session: data.session };
939
+ }
940
+ var LIVE_REFRESH_SKEW_S = 10 * 60;
941
+ async function authedSession(skewS = ACCESS_SKEW_S) {
942
+ const cached = loadAuth();
943
+ if (!cached) return null;
944
+ const reused = await reuseCached(cached, skewS);
945
+ if (reused) return reused;
946
+ const locked = await withAuthLock(async ({ stillMine }) => {
947
+ const auth = loadAuth();
948
+ if (!auth) return null;
949
+ const fresh = await reuseCached(auth, skewS);
950
+ if (fresh) return fresh;
951
+ if (!stillMine()) return null;
952
+ const db = newClient(auth);
953
+ const { data, error } = await db.auth.refreshSession({ refresh_token: auth.refreshToken });
954
+ if (error || !data.session) return null;
955
+ if (!data.session.refresh_token) {
956
+ process.stderr.write("inplan: refresh returned no new refresh token; keeping the stored one and retrying rather than persisting a possibly-spent token\n");
957
+ return null;
958
+ }
959
+ saveAuth({
960
+ ...auth,
961
+ refreshToken: data.session.refresh_token,
962
+ accessToken: data.session.access_token,
963
+ ...data.session.expires_at ? { expiresAt: data.session.expires_at } : {},
964
+ ...data.session.user?.email ? { email: data.session.user.email } : {}
965
+ });
966
+ return { db, session: data.session };
967
+ });
968
+ if (locked.acquired) return locked.value;
969
+ return reuseCached(loadAuth() ?? cached, 0);
863
970
  }
864
971
  async function currentUser() {
865
972
  const s = await authedSession();
@@ -872,8 +979,8 @@ async function currentUser() {
872
979
  ...name ? { name } : {}
873
980
  };
874
981
  }
875
- async function remoteBackend(docId, consumerId = "cli-agent") {
876
- const s = await authedSession();
982
+ async function remoteBackend(docId, consumerId = "cli-agent", skewS) {
983
+ const s = await authedSession(skewS);
877
984
  if (!s) return null;
878
985
  return {
879
986
  db: s.db,
@@ -882,6 +989,69 @@ async function remoteBackend(docId, consumerId = "cli-agent") {
882
989
  token: s.session.access_token
883
990
  };
884
991
  }
992
+ var REFRESH_BACKOFF_BASE_MS = 1e3;
993
+ var REFRESH_BACKOFF_MAX_MS = 6e4;
994
+ var refreshBackoffMs = (failures) => Math.min(REFRESH_BACKOFF_BASE_MS * 2 ** Math.max(0, failures - 1), REFRESH_BACKOFF_MAX_MS);
995
+ function liveRemoteBackend(docId, consumerId = "cli-agent") {
996
+ let inner = null;
997
+ let expiresAt = 0;
998
+ let inflight = null;
999
+ let failures = 0;
1000
+ let retryAfterMs = 0;
1001
+ const fresh = async () => {
1002
+ const now = Math.floor(Date.now() / 1e3);
1003
+ if (inner && expiresAt - now > LIVE_REFRESH_SKEW_S) return inner;
1004
+ if (Date.now() < retryAfterMs && !inflight) return inner && expiresAt > now ? inner : null;
1005
+ inflight ??= remoteBackend(docId, consumerId, LIVE_REFRESH_SKEW_S).then((b) => {
1006
+ if (b) {
1007
+ failures = 0;
1008
+ retryAfterMs = 0;
1009
+ inner = b;
1010
+ expiresAt = loadAuth()?.expiresAt ?? now + 300;
1011
+ return b;
1012
+ }
1013
+ failures += 1;
1014
+ retryAfterMs = Date.now() + refreshBackoffMs(failures);
1015
+ const stillLoggedIn = loadAuth() !== null;
1016
+ if (stillLoggedIn && inner && expiresAt > Math.floor(Date.now() / 1e3)) return inner;
1017
+ inner = null;
1018
+ expiresAt = 0;
1019
+ return null;
1020
+ }).finally(() => {
1021
+ inflight = null;
1022
+ });
1023
+ return inflight;
1024
+ };
1025
+ const need = async () => {
1026
+ const b = await fresh();
1027
+ if (!b) throw new Error("inplan: not logged in (or session expired) \u2014 run `inplan login`");
1028
+ return b;
1029
+ };
1030
+ const channel = {
1031
+ append: async (e, o) => (await need()).channel.append(e, o),
1032
+ readSince: async (c) => (await need()).channel.readSince(c),
1033
+ // The poll-based wait never subscribes; delegate best-effort to the current inner (a re-mint
1034
+ // doesn't migrate an active subscription — not needed on this path).
1035
+ subscribe: (cb) => inner?.channel.subscribe(cb) ?? (() => {
1036
+ }),
1037
+ getCursor: async () => (await need()).channel.getCursor(),
1038
+ setCursor: async (s) => (await need()).channel.setCursor(s),
1039
+ claimLock: async (t) => (await need()).channel.claimLock(t),
1040
+ isSuperseded: async (t) => (await need()).channel.isSuperseded(t),
1041
+ presence: async () => (await need()).channel.presence()
1042
+ };
1043
+ const store = {
1044
+ loadDoc: async () => (await need()).store.loadDoc(),
1045
+ saveDoc: async (c) => (await need()).store.saveDoc(c),
1046
+ getCanonical: async () => (await need()).store.getCanonical(),
1047
+ setCanonical: async (c) => (await need()).store.setCanonical(c),
1048
+ getProposed: async () => (await need()).store.getProposed(),
1049
+ setProposed: async (c) => (await need()).store.setProposed(c),
1050
+ clearProposed: async () => (await need()).store.clearProposed(),
1051
+ backup: async (c, m) => (await need()).store.backup(c, m)
1052
+ };
1053
+ return { channel, store, tokenNow: () => inner?.token ?? null };
1054
+ }
885
1055
 
886
1056
  // src/cliLogin.ts
887
1057
  import { createServer } from "http";
@@ -1053,9 +1223,13 @@ function compareVersions(a, b) {
1053
1223
  }
1054
1224
  return 0;
1055
1225
  }
1226
+ var REGISTRY_TIMEOUT_MS = 3e3;
1056
1227
  async function latestVersion(pkg) {
1057
1228
  try {
1058
- const res = await fetch(`https://registry.npmjs.org/${pkg.replace("/", "%2F")}/latest`, { headers: { accept: "application/json" } });
1229
+ const res = await fetch(`https://registry.npmjs.org/${pkg.replace("/", "%2F")}/latest`, {
1230
+ headers: { accept: "application/json" },
1231
+ signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS)
1232
+ });
1059
1233
  if (!res.ok) return null;
1060
1234
  const data = await res.json();
1061
1235
  return typeof data.version === "string" ? data.version : null;
@@ -1077,6 +1251,33 @@ function selfUpdate(pkg) {
1077
1251
  child.on("close", (code) => resolve4({ ok: code === 0, output: output2.trim() }));
1078
1252
  });
1079
1253
  }
1254
+ var STALENESS_TTL_MS = 6 * 60 * 60 * 1e3;
1255
+ async function warnIfOutdated(pkg, current, deps = {}) {
1256
+ const now = (deps.now ?? Date.now)();
1257
+ try {
1258
+ const cached = deps.readCache?.() ?? null;
1259
+ if (cached) {
1260
+ const { at, latest: latest2, pkg: cachedPkg } = JSON.parse(cached);
1261
+ if (typeof at === "number" && typeof latest2 === "string" && cachedPkg === pkg && at <= now && now - at < STALENESS_TTL_MS) {
1262
+ return compareVersions(current, latest2) < 0 ? emitOutdated(pkg, current, latest2) : null;
1263
+ }
1264
+ }
1265
+ } catch {
1266
+ }
1267
+ const latest = await (deps.fetchLatest ?? latestVersion)(pkg);
1268
+ if (latest === null) return null;
1269
+ try {
1270
+ deps.writeCache?.(JSON.stringify({ at: now, latest, pkg }));
1271
+ } catch {
1272
+ }
1273
+ return compareVersions(current, latest) < 0 ? emitOutdated(pkg, current, latest) : null;
1274
+ }
1275
+ function emitOutdated(pkg, current, latest) {
1276
+ const msg = `inplan: your CLI is ${current}; ${latest} is available. Some cloud documents need a newer CLI \u2014 update with \`npm i -g ${pkg}@latest\`.`;
1277
+ process.stderr.write(`${msg}
1278
+ `);
1279
+ return msg;
1280
+ }
1080
1281
 
1081
1282
  // src/editorProcess.ts
1082
1283
  function isProcessAlive2(pid) {
@@ -1232,35 +1433,95 @@ function addComment(currentText, input) {
1232
1433
  import { homedir as homedir5 } from "os";
1233
1434
  import { join as join7 } from "path";
1234
1435
  import { pathToFileURL } from "url";
1235
- var PLUGIN_HTTP = (process.env.INPLAN_PLUGIN_URL || "wss://inplan-collab.fly.dev").replace(/^ws/, "http");
1436
+ var DEFAULT_HUB_URL = "wss://inplan-collab.fly.dev";
1437
+ var resolveHubUrl = () => process.env.INPLAN_PLUGIN_URL || process.env.INPLAN_COLLAB_URL || DEFAULT_HUB_URL;
1438
+ var PLUGIN_HTTP = resolveHubUrl().replace(/^ws/, "http");
1236
1439
  var defaultCacheDir = () => join7(process.env.INPLAN_HOME || join7(homedir5(), ".inplan"), "plugin-cache");
1237
1440
  var defaultDeps = {
1238
- resolve: resolveDesktopPlugin,
1441
+ resolve: resolvePluginOutcome,
1239
1442
  importCli: (p) => import(pathToFileURL(p).href)
1240
1443
  };
1241
- async function loadPluginGate(session, options, deps = defaultDeps) {
1444
+ async function loadPluginGateOutcome(session, options, deps = defaultDeps) {
1242
1445
  try {
1243
- const bundle = await deps.resolve({
1446
+ const { plugin, reason } = await deps.resolve({
1244
1447
  apiBase: options.apiBase ?? PLUGIN_HTTP,
1245
1448
  token: options.token,
1246
1449
  cacheDir: options.cacheDir ?? defaultCacheDir(),
1247
- ...options.publicKey ? { publicKey: options.publicKey } : {}
1450
+ // Forward whenever DEFINED, not whenever truthy: an explicit `""` means "nothing can be
1451
+ // verified" and must reach the resolver, which then refuses without a network call. Dropping
1452
+ // it would silently substitute the baked-in key and verify against something the caller
1453
+ // deliberately disabled.
1454
+ ...options.publicKey !== void 0 ? { publicKey: options.publicKey } : {}
1248
1455
  });
1249
- const cliName = bundle?.entries.cli;
1250
- const cliPath = cliName ? bundle?.files[cliName] : void 0;
1251
- if (!cliPath) return null;
1456
+ if (!plugin) return { gate: null, reason };
1457
+ const cliName = plugin.entries.cli;
1458
+ const cliPath = cliName ? plugin.files[cliName] : void 0;
1459
+ if (!cliPath) return { gate: null, reason: "unavailable" };
1252
1460
  const cli = await deps.importCli(cliPath);
1253
- return cli.gate(session);
1461
+ return { gate: cli.gate(session), reason: null };
1462
+ } catch {
1463
+ return { gate: null, reason: "unavailable" };
1464
+ }
1465
+ }
1466
+ async function loadPluginGate(session, options, deps = defaultDeps) {
1467
+ try {
1468
+ return (await loadPluginGateOutcome(session, options, deps)).gate;
1254
1469
  } catch {
1255
1470
  return null;
1256
1471
  }
1257
1472
  }
1258
1473
 
1474
+ // src/liveSync.ts
1475
+ function shouldHydrateWorkFile(o) {
1476
+ if (!o.exists) return true;
1477
+ if (o.pending) return false;
1478
+ return o.currentHash != null && o.currentHash === o.syncedHash;
1479
+ }
1480
+ function pendingRequiresReplay(o) {
1481
+ return o.writeFailed;
1482
+ }
1483
+ function trackGateDegradations(gate, localStore, onWriteError) {
1484
+ let readFailed = false;
1485
+ let writeFailed = false;
1486
+ return {
1487
+ readFailed: () => readFailed,
1488
+ writeFailed: () => writeFailed,
1489
+ gate: {
1490
+ readCanonical: async () => {
1491
+ try {
1492
+ return await gate.readCanonical();
1493
+ } catch (e) {
1494
+ readFailed = true;
1495
+ throw e;
1496
+ }
1497
+ },
1498
+ applyRevision: async (md) => {
1499
+ try {
1500
+ await gate.applyRevision(md);
1501
+ } catch (e) {
1502
+ writeFailed = true;
1503
+ onWriteError?.(String(e));
1504
+ await localStore.setCanonical(md);
1505
+ await localStore.saveDoc(md);
1506
+ }
1507
+ }
1508
+ }
1509
+ };
1510
+ }
1511
+ function postTurnAction(outcome, degraded) {
1512
+ if (outcome === "exiting") return "stop";
1513
+ return degraded.readFailed || degraded.writeFailed ? "keep-local" : "resync";
1514
+ }
1515
+ function demoteSource({ hubReadable, fromStore }) {
1516
+ if (hubReadable) return { use: "hub" };
1517
+ return fromStore ? { use: "store" } : { use: "abort", reason: "hub_unreadable" };
1518
+ }
1519
+
1259
1520
  // src/presence.ts
1260
1521
  import { HocuspocusProvider, HocuspocusProviderWebsocket } from "@hocuspocus/provider";
1261
1522
  import * as Y from "yjs";
1262
1523
  import WebSocket2 from "ws";
1263
- var COLLAB_URL = process.env.INPLAN_COLLAB_URL || "wss://inplan-collab.fly.dev";
1524
+ var COLLAB_URL = resolveHubUrl();
1264
1525
  function announcePresence(docId, token, model) {
1265
1526
  try {
1266
1527
  const ydoc = new Y.Doc();
@@ -1284,6 +1545,36 @@ function announcePresence(docId, token, model) {
1284
1545
  }
1285
1546
 
1286
1547
  // src/wait.ts
1548
+ var DEFAULT_ERROR_GRACE_MS = 5 * 6e4;
1549
+ var DEFAULT_POLL_TIMEOUT_MS = 3e4;
1550
+ function inFlightGate() {
1551
+ let pending = 0;
1552
+ return {
1553
+ busy: () => pending > 0,
1554
+ run: (start, ms) => {
1555
+ pending += 1;
1556
+ const underlying = start();
1557
+ void underlying.then(
1558
+ () => pending -= 1,
1559
+ () => pending -= 1
1560
+ );
1561
+ return withTimeout(underlying, ms);
1562
+ }
1563
+ };
1564
+ }
1565
+ async function withTimeout(p, ms) {
1566
+ let timer;
1567
+ try {
1568
+ return await Promise.race([
1569
+ p,
1570
+ new Promise((_res, rej) => {
1571
+ timer = setTimeout(() => rej(new Error(`poll timed out after ${ms}ms`)), ms);
1572
+ })
1573
+ ]);
1574
+ } finally {
1575
+ if (timer) clearTimeout(timer);
1576
+ }
1577
+ }
1287
1578
  var defaultActionable = (e) => e.actor === "user";
1288
1579
  function wakePredicate(wake) {
1289
1580
  return wake === "any-action" ? (e) => e.actor === "user" && e.type !== LogEventType.SettingsChanged : (e) => e.type === LogEventType.TurnEnded || e.type === LogEventType.SessionClosed || e.type === LogEventType.SaveLocallyRequested || e.type === LogEventType.NavigatedTo;
@@ -1293,6 +1584,9 @@ function waitForActions(opts) {
1293
1584
  const pollMs2 = opts.pollMs ?? 200;
1294
1585
  const isActionable = opts.isActionable ?? defaultActionable;
1295
1586
  const watchEditor = opts.watchEditor ?? true;
1587
+ const errorGraceMs = opts.errorGraceMs ?? DEFAULT_ERROR_GRACE_MS;
1588
+ const pollTimeoutMs = opts.pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS;
1589
+ const now = opts.now ?? Date.now;
1296
1590
  const ch = opts.channel;
1297
1591
  return new Promise((resolve4, reject) => {
1298
1592
  let deadline = null;
@@ -1300,6 +1594,10 @@ function waitForActions(opts) {
1300
1594
  let sawEditorAlive = false;
1301
1595
  let busy = false;
1302
1596
  let done = false;
1597
+ let failingSince = null;
1598
+ const reads = inFlightGate();
1599
+ const locks = inFlightGate();
1600
+ const presences = inFlightGate();
1303
1601
  const cleanup = () => {
1304
1602
  clearInterval(timer);
1305
1603
  opts.signal?.removeEventListener("abort", onAbort);
@@ -1318,13 +1616,19 @@ function waitForActions(opts) {
1318
1616
  };
1319
1617
  const tick = async () => {
1320
1618
  if (busy || done) return;
1619
+ if (reads.busy()) {
1620
+ const at = now();
1621
+ failingSince ??= at;
1622
+ if (at - failingSince >= errorGraceMs) finish({ entries: [], cursor: opts.cursor, failed: new Error("polls timed out and are still in flight") });
1623
+ return;
1624
+ }
1321
1625
  busy = true;
1322
1626
  try {
1323
- const { entries, cursor } = await ch.readSince(opts.cursor);
1627
+ const { entries, cursor } = await reads.run(() => ch.readSince(opts.cursor), pollTimeoutMs);
1324
1628
  if (done) return;
1325
1629
  if (opts.token) {
1326
1630
  try {
1327
- if (await ch.isSuperseded(opts.token)) {
1631
+ if (!locks.busy() && await locks.run(() => ch.isSuperseded(opts.token), pollTimeoutMs)) {
1328
1632
  finish({ entries, cursor, superseded: true });
1329
1633
  return;
1330
1634
  }
@@ -1332,13 +1636,13 @@ function waitForActions(opts) {
1332
1636
  }
1333
1637
  }
1334
1638
  if (watchEditor) {
1335
- let alive = false;
1639
+ let alive;
1336
1640
  try {
1337
- alive = await ch.presence();
1641
+ if (!presences.busy()) alive = await presences.run(() => ch.presence(), pollTimeoutMs);
1338
1642
  } catch {
1339
1643
  }
1340
- if (alive) sawEditorAlive = true;
1341
- else if (sawEditorAlive) {
1644
+ if (alive === true) sawEditorAlive = true;
1645
+ else if (alive === false && sawEditorAlive) {
1342
1646
  finish({ entries, cursor, editorGone: true });
1343
1647
  return;
1344
1648
  }
@@ -1351,6 +1655,13 @@ function waitForActions(opts) {
1351
1655
  finish({ entries, cursor });
1352
1656
  }
1353
1657
  }
1658
+ failingSince = null;
1659
+ } catch (e) {
1660
+ const at = now();
1661
+ failingSince ??= at;
1662
+ if (at - failingSince >= errorGraceMs) {
1663
+ finish({ entries: [], cursor: opts.cursor, failed: e instanceof Error ? e : new Error(String(e)) });
1664
+ }
1354
1665
  } finally {
1355
1666
  busy = false;
1356
1667
  }
@@ -1453,6 +1764,9 @@ var VERSION = versionFromModule(import.meta.url);
1453
1764
  function output(obj) {
1454
1765
  process.stdout.write(JSON.stringify(obj) + "\n");
1455
1766
  }
1767
+ function exitAfterFlush(code, out = process.stdout, exit = process.exit, err = process.stderr) {
1768
+ out.write("", () => err.write("", () => exit(code)));
1769
+ }
1456
1770
  function getFlag(args, name) {
1457
1771
  const withEq = args.find((a) => a.startsWith(`--${name}=`));
1458
1772
  if (withEq) return withEq.slice(name.length + 3);
@@ -1499,7 +1813,7 @@ function cachedElectronZip(version, platform, arch) {
1499
1813
  for (const sub of readdirSync2(root)) {
1500
1814
  const f = join9(root, sub, want);
1501
1815
  if (!existsSync9(f)) continue;
1502
- const mtime = statSync2(f).mtimeMs;
1816
+ const mtime = statSync3(f).mtimeMs;
1503
1817
  if (!best || mtime > best.mtime) best = { file: f, mtime };
1504
1818
  }
1505
1819
  return best?.file ?? null;
@@ -1660,11 +1974,13 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1660
1974
  message: "Edit removes anchored comment(s). Re-run wait with --confirmed-comment-deletion=<ids> to proceed.",
1661
1975
  lost: ev.unconfirmed.map((c) => ({ id: c.id, text: c.text, author: c.author }))
1662
1976
  });
1663
- process.exit(3);
1977
+ exitAfterFlush(3);
1978
+ return "exiting";
1664
1979
  }
1665
1980
  if (!ev.integrityOk) {
1666
1981
  output({ status: "integrity_error", errors: ev.integrityErrors });
1667
- process.exit(2);
1982
+ exitAfterFlush(2);
1983
+ return "exiting";
1668
1984
  }
1669
1985
  const acceptance = acceptanceFrom(history);
1670
1986
  const quarantine = acceptance === "review" && parse(canonicalText).body !== parse(current).body;
@@ -1681,23 +1997,32 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1681
1997
  const mode = modeFrom(history);
1682
1998
  const isActionable = wakePredicate(mode.wake);
1683
1999
  const result = await waitForActions({ channel, cursor, debounceMs, pollMs, isActionable, token: lockToken });
2000
+ if (result.failed) {
2001
+ backend.logExit("poll_failed");
2002
+ process.stderr.write(`inplan: lost contact with the document (${result.failed.message}).
2003
+ If your session expired, run \`inplan login\` and re-attach.
2004
+ `);
2005
+ output({ status: "wait_failed", message: result.failed.message });
2006
+ exitAfterFlush(EXIT_WAIT_FAILED);
2007
+ return "exiting";
2008
+ }
1684
2009
  if (result.superseded) {
1685
2010
  backend.logExit("superseded");
1686
2011
  output({ status: "superseded" });
1687
- return;
2012
+ return "ok";
1688
2013
  }
1689
- await channel.setCursor(result.cursor);
1690
2014
  if (backend.onSaveLocally && result.entries.some((e) => e.type === LogEventType.SaveLocallyRequested)) {
1691
2015
  backend.logExit("save_locally");
1692
2016
  await backend.onSaveLocally();
1693
- return;
2017
+ return "ok";
1694
2018
  }
2019
+ await channel.setCursor(result.cursor);
1695
2020
  const navEntry = result.entries.find((e) => e.type === LogEventType.NavigatedTo);
1696
2021
  if (navEntry) {
1697
2022
  const path = navEntry.payload?.path;
1698
2023
  backend.logExit("navigated");
1699
2024
  output({ status: "navigated", ...path ? { path } : {}, cursor: result.cursor, closed: false });
1700
- return;
2025
+ return "ok";
1701
2026
  }
1702
2027
  const closeEntry = result.entries.find((e) => e.type === LogEventType.SessionClosed);
1703
2028
  let status;
@@ -1727,6 +2052,7 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1727
2052
  closed: status === "closed",
1728
2053
  entries: result.entries
1729
2054
  });
2055
+ return "ok";
1730
2056
  }
1731
2057
  async function doLogin(args) {
1732
2058
  const url = getFlag(args, "url") ?? process.env.INPLAN_SUPABASE_URL;
@@ -1740,10 +2066,7 @@ async function doLogin(args) {
1740
2066
  return;
1741
2067
  }
1742
2068
  try {
1743
- const auth = await browserLogin({ onUrl: (u) => process.stderr.write(`Opening your browser to sign in:
1744
- ${u}
1745
- If it didn't open, paste that URL into your browser.
1746
- `) });
2069
+ const auth = await defaultBrowserLogin();
1747
2070
  saveAuth(auth);
1748
2071
  await persistCloudIdentity();
1749
2072
  output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
@@ -1761,7 +2084,67 @@ async function persistCloudIdentity() {
1761
2084
  } catch {
1762
2085
  }
1763
2086
  }
2087
+ function canInteractiveLogin(args) {
2088
+ if (hasFlag(args, "no-login")) return false;
2089
+ if (process.env.CI || process.env.INPLAN_NO_BROWSER) return false;
2090
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
2091
+ }
2092
+ async function ensureLoggedIn(args, login = defaultBrowserLogin) {
2093
+ if (loadAuth()) return true;
2094
+ if (!canInteractiveLogin(args)) return false;
2095
+ try {
2096
+ process.stderr.write("inplan: not signed in \u2014 opening your browser to sign in\u2026\n");
2097
+ saveAuth(await login());
2098
+ await persistCloudIdentity();
2099
+ return true;
2100
+ } catch (e) {
2101
+ process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2102
+ `);
2103
+ return false;
2104
+ }
2105
+ }
2106
+ function defaultBrowserLogin() {
2107
+ return browserLogin({ onUrl: (u) => process.stderr.write(`Opening your browser to sign in:
2108
+ ${u}
2109
+ If it didn't open, paste that URL into your browser.
2110
+ `) });
2111
+ }
2112
+ function stalenessCache() {
2113
+ const path = join9(sidecarRoot(), ".update-check.json");
2114
+ return {
2115
+ readCache: () => existsSync9(path) ? readFileSync9(path, "utf8") : null,
2116
+ writeCache: (v) => {
2117
+ mkdirSync8(dirname9(path), { recursive: true });
2118
+ writeFileSync8(path, v);
2119
+ }
2120
+ };
2121
+ }
2122
+ var EXIT_UPGRADE_REQUIRED = 4;
2123
+ var EXIT_PLUGIN_UNAVAILABLE = 5;
2124
+ var EXIT_WAIT_FAILED = 6;
2125
+ function shellQuote(path) {
2126
+ return "'" + path.replaceAll("'", "'\\''") + "'";
2127
+ }
2128
+ function explainNoGate(reason, localFile) {
2129
+ if (reason === "unentitled") {
2130
+ process.stderr.write(
2131
+ "inplan: this plan doesn't include the local agent on cloud documents.\n Open the document in your browser and click the agent indicator to upgrade.\n" + (localFile ? ` Or keep working offline for free: \`inplan demote ${shellQuote(localFile)}\` brings it back to disk.
2132
+ ` : "")
2133
+ );
2134
+ output({ status: "upgrade_required", reason, ...localFile ? { localFile } : {} });
2135
+ return;
2136
+ }
2137
+ process.stderr.write(
2138
+ "inplan: couldn't verify your plan for this cloud document (offline, or the service is down).\n This is not a plan limit \u2014 retry in a moment.\n" + (localFile ? ` To work offline meanwhile: \`inplan demote ${shellQuote(localFile)}\`.
2139
+ ` : "")
2140
+ );
2141
+ output({ status: "plugin_unavailable", reason, ...localFile ? { localFile } : {} });
2142
+ }
1764
2143
  async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile, model) {
2144
+ if (!await ensureLoggedIn(rest)) {
2145
+ process.stderr.write("inplan: not logged in (or session expired) \u2014 run `inplan login`\n");
2146
+ process.exit(1);
2147
+ }
1765
2148
  const backend = await remoteBackend(docId, "cli-agent");
1766
2149
  if (!backend) {
1767
2150
  process.stderr.write("inplan: not logged in (or session expired) \u2014 run `inplan login`\n");
@@ -1793,29 +2176,105 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
1793
2176
  output({ status: "messaged" });
1794
2177
  return;
1795
2178
  }
1796
- const onSaveLocally = localFile ? async () => {
1797
- const body = await backend.store.loadDoc();
1798
- writeFileSync8(localFile, body);
1799
- writeStatus(docPaths(localFile).statusPath, { location: "local", originalPath: localFile, lastSyncedHash: hashBody(body) });
1800
- const pid = spawnApp(localFile);
1801
- output({ status: "moved_local", path: localFile, reopened: pid !== null });
1802
- } : void 0;
2179
+ await warnIfOutdated(UPDATE_PKG, VERSION, stalenessCache());
2180
+ const live = liveRemoteBackend(docId, "cli-agent");
2181
+ const hubUrl = resolveHubUrl();
2182
+ const hubSession = JSON.stringify({ url: hubUrl, docName: docId, token: backend.token });
2183
+ const { gate, reason } = await loadPluginGateOutcome(hubSession, { token: backend.token });
2184
+ if (!gate) {
2185
+ explainNoGate(reason, localFile);
2186
+ exitAfterFlush(reason === "unentitled" ? EXIT_UPGRADE_REQUIRED : EXIT_PLUGIN_UNAVAILABLE);
2187
+ return;
2188
+ }
1803
2189
  const presence = announcePresence(docId, backend.token, model);
1804
2190
  try {
1805
- await waitCycle(
2191
+ const workFile = join9(sidecarRoot(), "remote", `${docId}.plan.md`);
2192
+ const pendingPath = `${workFile}.pending`;
2193
+ const hashPath = `${workFile}.synced`;
2194
+ mkdirSync8(dirname9(workFile), { recursive: true });
2195
+ const readIf = (p) => existsSync9(p) ? readFileSync9(p, "utf8") : null;
2196
+ const recordSynced = (content) => writeFileSync8(hashPath, hashBody(content));
2197
+ let canonical = "";
2198
+ try {
2199
+ canonical = await gate.readCanonical();
2200
+ } catch (e) {
2201
+ process.stderr.write(`inplan: live-collab hub unreachable (${String(e)})
2202
+ `);
2203
+ explainNoGate("unavailable", localFile);
2204
+ exitAfterFlush(EXIT_PLUGIN_UNAVAILABLE);
2205
+ return;
2206
+ }
2207
+ const exists = existsSync9(workFile);
2208
+ if (shouldHydrateWorkFile({
2209
+ exists,
2210
+ pending: existsSync9(pendingPath),
2211
+ currentHash: exists ? hashBody(readFileSync9(workFile, "utf8")) : null,
2212
+ syncedHash: readIf(hashPath)
2213
+ })) {
2214
+ writeFileSync8(workFile, canonical);
2215
+ recordSynced(canonical);
2216
+ }
2217
+ const localStore = fsBackend(workFile).store;
2218
+ const gateStore = {
2219
+ loadDoc: () => localStore.loadDoc(),
2220
+ saveDoc: (c) => localStore.saveDoc(c),
2221
+ getCanonical: () => localStore.getCanonical(),
2222
+ setCanonical: (c) => localStore.setCanonical(c),
2223
+ backup: (c, m) => localStore.backup(c, m),
2224
+ getProposed: () => live.store.getProposed(),
2225
+ setProposed: (c) => live.store.setProposed(c),
2226
+ clearProposed: () => live.store.clearProposed()
2227
+ };
2228
+ const onSaveLocallyGate = localFile ? async () => {
2229
+ const body = await gate.readCanonical();
2230
+ writeFileSync8(localFile, body);
2231
+ writeStatus(docPaths(localFile).statusPath, { location: "local", originalPath: localFile, lastSyncedHash: hashBody(body) });
2232
+ const pid = spawnApp(localFile);
2233
+ output({ status: "moved_local", path: localFile, reopened: pid !== null });
2234
+ } : void 0;
2235
+ const tracked = trackGateDegradations(
2236
+ gate,
2237
+ localStore,
2238
+ (m) => process.stderr.write(`inplan: live-collab hub write failed (${m}); kept the edit locally to retry
2239
+ `)
2240
+ );
2241
+ process.stderr.write(`inplan: live-collab \u2014 plan at ${workFile}; read/edit it there, then re-run to sync
2242
+ `);
2243
+ const outcome = await waitCycle(
1806
2244
  {
1807
- channel: backend.channel,
1808
- store: backend.store,
1809
- history: async () => (await backend.channel.readSince(0)).entries,
2245
+ channel: live.channel,
2246
+ // turns/comments still ride the cloud control log (self-refreshing)…
2247
+ store: gateStore,
2248
+ // …the agent reads/edits a local working copy; proposals go to the cloud…
2249
+ history: async () => (await live.channel.readSince(0)).entries,
1810
2250
  logExit: () => {
1811
2251
  },
1812
- // no local sidecar for a cloud doc
1813
- ...onSaveLocally ? { onSaveLocally } : {}
2252
+ ...onSaveLocallyGate ? { onSaveLocally: onSaveLocallyGate } : {}
1814
2253
  },
1815
2254
  explicitCursor,
1816
2255
  confirmed,
1817
- model
2256
+ model,
2257
+ tracked.gate
2258
+ // …and accepted edits apply through the hub, not the store.
1818
2259
  );
2260
+ const action = postTurnAction(outcome, { readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() });
2261
+ if (action === "stop") return;
2262
+ if (action === "keep-local") {
2263
+ if (pendingRequiresReplay({ readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() })) {
2264
+ writeFileSync8(pendingPath, "1");
2265
+ }
2266
+ process.stderr.write("inplan: hub was unavailable this turn \u2014 keeping local edits (will sync next turn)\n");
2267
+ } else {
2268
+ if (existsSync9(pendingPath)) rmSync2(pendingPath);
2269
+ recordSynced(readFileSync9(workFile, "utf8"));
2270
+ try {
2271
+ const fresh = await gate.readCanonical();
2272
+ writeFileSync8(workFile, fresh);
2273
+ recordSynced(fresh);
2274
+ } catch {
2275
+ }
2276
+ }
2277
+ return;
1819
2278
  } finally {
1820
2279
  presence.destroy();
1821
2280
  }
@@ -1851,11 +2310,32 @@ async function doDemote(file, args) {
1851
2310
  process.stderr.write("inplan: not logged in (or session expired) \u2014 run `inplan login`\n");
1852
2311
  process.exit(1);
1853
2312
  }
1854
- const body = await backend.store.loadDoc();
2313
+ const hubSession = JSON.stringify({ url: resolveHubUrl(), docName: st.cloudDocId, token: backend.token });
2314
+ const { gate } = await loadPluginGateOutcome(hubSession, { token: backend.token });
2315
+ let hubBody = null;
2316
+ try {
2317
+ if (gate) hubBody = await gate.readCanonical();
2318
+ } catch {
2319
+ hubBody = null;
2320
+ }
1855
2321
  const dest = st.originalPath ?? file;
2322
+ const choice = demoteSource({ hubReadable: hubBody !== null, fromStore: hasFlag(args, "from-store") });
2323
+ if (choice.use === "abort") {
2324
+ process.stderr.write(
2325
+ `inplan demote: couldn't read the live document from the collab hub.
2326
+ The server copy may be missing edits made through the hub, and demoting overwrites ${shellQuote(dest)}
2327
+ and switches the document to local \u2014 together, that can't be undone.
2328
+ Retry when the hub is reachable, or re-run with --from-store to accept the server copy as-is.
2329
+ `
2330
+ );
2331
+ output({ status: "demote_blocked", reason: choice.reason, path: dest });
2332
+ exitAfterFlush(EXIT_PLUGIN_UNAVAILABLE);
2333
+ return;
2334
+ }
2335
+ const body = choice.use === "hub" ? hubBody : await backend.store.loadDoc();
1856
2336
  writeFileSync8(dest, body);
1857
2337
  writeStatus(p.statusPath, { location: "local", originalPath: dest, lastSyncedHash: hashBody(body) });
1858
- output({ status: "demoted", location: "local", path: dest });
2338
+ output({ status: "demoted", location: "local", path: dest, source: choice.use });
1859
2339
  }
1860
2340
  function firstHeading(body) {
1861
2341
  return body.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() || null;
@@ -1915,7 +2395,7 @@ function activeDocForCwd(cwd) {
1915
2395
  const rel = relative4(base2, real(orig));
1916
2396
  if (rel === "" || rel.startsWith("..") || isAbsolute2(rel)) continue;
1917
2397
  const logPath = join9(dir, "log.jsonl");
1918
- const mtime = existsSync9(logPath) ? statSync2(logPath).mtimeMs : 0;
2398
+ const mtime = existsSync9(logPath) ? statSync3(logPath).mtimeMs : 0;
1919
2399
  if (!best || mtime > best.mtime) best = { file: resolve3(orig), mtime };
1920
2400
  } catch {
1921
2401
  }
@@ -2100,7 +2580,7 @@ function grantClaudePermissions(claudeRoot) {
2100
2580
  try {
2101
2581
  const tmp = settingsPath + ".tmp";
2102
2582
  writeFileSync8(tmp, JSON.stringify(settings, null, 2) + "\n");
2103
- renameSync(tmp, settingsPath);
2583
+ renameSync2(tmp, settingsPath);
2104
2584
  } catch {
2105
2585
  return false;
2106
2586
  }
@@ -2158,7 +2638,7 @@ function writeJsonAtomic(path, value) {
2158
2638
  mkdirSync8(dirname9(path), { recursive: true });
2159
2639
  const tmp = path + ".tmp";
2160
2640
  writeFileSync8(tmp, JSON.stringify(value, null, 2) + "\n");
2161
- renameSync(tmp, path);
2641
+ renameSync2(tmp, path);
2162
2642
  return true;
2163
2643
  } catch {
2164
2644
  return false;
@@ -2231,7 +2711,7 @@ function installPiRelayExtension(piAgentRoot) {
2231
2711
  mkdirSync8(dirname9(path), { recursive: true });
2232
2712
  const tmp = path + ".tmp";
2233
2713
  writeFileSync8(tmp, PI_RELAY_EXTENSION);
2234
- renameSync(tmp, path);
2714
+ renameSync2(tmp, path);
2235
2715
  return true;
2236
2716
  } catch {
2237
2717
  return false;
@@ -2429,7 +2909,7 @@ async function main() {
2429
2909
  );
2430
2910
  if (!cmd || !["open", "wait", "signal", "message", "comment", "relay", "status", "promote", "demote", "upload"].includes(cmd)) {
2431
2911
  process.stderr.write(
2432
- 'usage: inplan <open|wait|signal> <file|--remote DOC_ID> [--model NAME] [--cursor N] [--confirmed-comment-deletion=a,b] [--done] [--reload]\n inplan message <file> "your message" (relay a note to the editor status bar)\n inplan comment <file> (--parent-id <id>|--doc|--span "text") --text "..." [--model NAME] [--may-resolve] [--question <json>]\n inplan relay [--hook <kind> | --text <s> [--activity]] (agent-hook \u2192 editor; resolves the active doc)\n inplan status <file>\n inplan upload <file> [--org <slug>] [--repo <name>] [--path <p>] [--evict-lru] (Collaborate on Cloud)\n inplan promote <file> --cloud-doc <docId> [--locator org/repo/path]\n inplan demote <file>\n inplan login (opens the browser to sign in; or --url <url> --anon <key> --refresh <token> for scripts)\n inplan whoami | logout\n'
2912
+ 'usage: inplan open <file> (create/open a local plan in the editor)\n inplan wait <file|--remote DOC_ID> [--model NAME] [--cursor N] [--confirmed-comment-deletion=a,b] [--done] [--reload]\n inplan signal <file|--remote DOC_ID> [--done] [--reload]\n inplan message <file> "your message" (relay a note to the editor status bar)\n inplan comment <file> (--parent-id <id>|--doc|--span "text") --text "..." [--model NAME] [--may-resolve] [--question <json>]\n inplan relay [--hook <kind> | --text <s> [--activity]] (agent-hook \u2192 editor; resolves the active doc)\n inplan status <file>\n inplan upload <file> [--org <slug>] [--repo <name>] [--path <p>] [--evict-lru] (Collaborate on Cloud)\n inplan promote <file> --cloud-doc <docId> [--locator org/repo/path]\n inplan demote <file> [--from-store] (bring a cloud doc back to disk; --from-store accepts the server copy when the hub is unreadable)\n inplan login (opens the browser to sign in; or --url <url> --anon <key> --refresh <token> for scripts)\n inplan whoami | logout\n'
2433
2913
  );
2434
2914
  process.exit(64);
2435
2915
  }
@@ -2440,7 +2920,11 @@ async function main() {
2440
2920
  const remoteDocId = getFlag(args, "remote");
2441
2921
  if (remoteDocId) {
2442
2922
  rejectCommentOnCloud(cmd, false);
2443
- await runRemote(cmd, remoteDocId, explicitCursor, confirmed, args, void 0, model);
2923
+ const remoteCmd = cmd === "open" ? "wait" : cmd;
2924
+ if (cmd === "open") {
2925
+ process.stderr.write("inplan: `open --remote` is deprecated (a cloud doc has no local editor to launch) \u2014 use `wait --remote`. Attaching as `wait`.\n");
2926
+ }
2927
+ await runRemote(remoteCmd, remoteDocId, explicitCursor, confirmed, args, void 0, model);
2444
2928
  return;
2445
2929
  }
2446
2930
  const file = argv[1] ? resolve3(argv[1]) : argv[1];
@@ -2589,15 +3073,34 @@ function isProgramEntry() {
2589
3073
  }
2590
3074
  }
2591
3075
  if (isProgramEntry()) {
3076
+ let exitingForUnhandledRejection = false;
3077
+ process.on("unhandledRejection", (reason) => {
3078
+ if (exitingForUnhandledRejection) return;
3079
+ exitingForUnhandledRejection = true;
3080
+ const message = reason instanceof Error ? reason.message : String(reason);
3081
+ process.stderr.write(`inplan: unexpected error \u2014 ${message}
3082
+ `);
3083
+ output({ status: "internal_error", message });
3084
+ exitAfterFlush(1);
3085
+ });
2592
3086
  main().catch((err) => {
2593
3087
  process.stderr.write(`inplan: ${err.message}
2594
3088
  `);
2595
- process.exit(1);
3089
+ output({ status: "internal_error", message: err.message });
3090
+ exitAfterFlush(1);
2596
3091
  });
2597
3092
  }
2598
3093
  export {
3094
+ EXIT_PLUGIN_UNAVAILABLE,
3095
+ EXIT_UPGRADE_REQUIRED,
3096
+ EXIT_WAIT_FAILED,
2599
3097
  activeDocForCwd,
3098
+ canInteractiveLogin,
2600
3099
  doUpload,
3100
+ ensureLoggedIn,
3101
+ exitAfterFlush,
3102
+ explainNoGate,
2601
3103
  notesFromHook,
3104
+ shellQuote,
2602
3105
  transcriptTextBlocks
2603
3106
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inplan",
3
- "version": "0.1.25",
3
+ "version": "0.1.27",
4
4
  "description": "inplan — a Markdown editor for human ⇄ coding-agent planning. CLI + desktop editor.",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "repository": {