inplan 0.1.26 → 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` if you haven't yet, 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-CJjtgrEi.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
@@ -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
@@ -930,23 +937,28 @@ async function reuseCached(auth, skewS = ACCESS_SKEW_S) {
930
937
  const { data, error } = await db.auth.setSession({ access_token: auth.accessToken, refresh_token: auth.refreshToken });
931
938
  return error || !data.session ? null : { db, session: data.session };
932
939
  }
933
- async function authedSession() {
940
+ var LIVE_REFRESH_SKEW_S = 10 * 60;
941
+ async function authedSession(skewS = ACCESS_SKEW_S) {
934
942
  const cached = loadAuth();
935
943
  if (!cached) return null;
936
- const reused = await reuseCached(cached);
944
+ const reused = await reuseCached(cached, skewS);
937
945
  if (reused) return reused;
938
946
  const locked = await withAuthLock(async ({ stillMine }) => {
939
947
  const auth = loadAuth();
940
948
  if (!auth) return null;
941
- const fresh = await reuseCached(auth);
949
+ const fresh = await reuseCached(auth, skewS);
942
950
  if (fresh) return fresh;
943
951
  if (!stillMine()) return null;
944
952
  const db = newClient(auth);
945
953
  const { data, error } = await db.auth.refreshSession({ refresh_token: auth.refreshToken });
946
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
+ }
947
959
  saveAuth({
948
960
  ...auth,
949
- refreshToken: data.session.refresh_token || auth.refreshToken,
961
+ refreshToken: data.session.refresh_token,
950
962
  accessToken: data.session.access_token,
951
963
  ...data.session.expires_at ? { expiresAt: data.session.expires_at } : {},
952
964
  ...data.session.user?.email ? { email: data.session.user.email } : {}
@@ -967,8 +979,8 @@ async function currentUser() {
967
979
  ...name ? { name } : {}
968
980
  };
969
981
  }
970
- async function remoteBackend(docId, consumerId = "cli-agent") {
971
- const s = await authedSession();
982
+ async function remoteBackend(docId, consumerId = "cli-agent", skewS) {
983
+ const s = await authedSession(skewS);
972
984
  if (!s) return null;
973
985
  return {
974
986
  db: s.db,
@@ -977,19 +989,29 @@ async function remoteBackend(docId, consumerId = "cli-agent") {
977
989
  token: s.session.access_token
978
990
  };
979
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);
980
995
  function liveRemoteBackend(docId, consumerId = "cli-agent") {
981
996
  let inner = null;
982
997
  let expiresAt = 0;
983
998
  let inflight = null;
999
+ let failures = 0;
1000
+ let retryAfterMs = 0;
984
1001
  const fresh = async () => {
985
1002
  const now = Math.floor(Date.now() / 1e3);
986
- if (inner && expiresAt - now > ACCESS_SKEW_S) return inner;
987
- inflight ??= remoteBackend(docId, consumerId).then((b) => {
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) => {
988
1006
  if (b) {
1007
+ failures = 0;
1008
+ retryAfterMs = 0;
989
1009
  inner = b;
990
1010
  expiresAt = loadAuth()?.expiresAt ?? now + 300;
991
1011
  return b;
992
1012
  }
1013
+ failures += 1;
1014
+ retryAfterMs = Date.now() + refreshBackoffMs(failures);
993
1015
  const stillLoggedIn = loadAuth() !== null;
994
1016
  if (stillLoggedIn && inner && expiresAt > Math.floor(Date.now() / 1e3)) return inner;
995
1017
  inner = null;
@@ -1201,9 +1223,13 @@ function compareVersions(a, b) {
1201
1223
  }
1202
1224
  return 0;
1203
1225
  }
1226
+ var REGISTRY_TIMEOUT_MS = 3e3;
1204
1227
  async function latestVersion(pkg) {
1205
1228
  try {
1206
- 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
+ });
1207
1233
  if (!res.ok) return null;
1208
1234
  const data = await res.json();
1209
1235
  return typeof data.version === "string" ? data.version : null;
@@ -1225,6 +1251,33 @@ function selfUpdate(pkg) {
1225
1251
  child.on("close", (code) => resolve4({ ok: code === 0, output: output2.trim() }));
1226
1252
  });
1227
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
+ }
1228
1281
 
1229
1282
  // src/editorProcess.ts
1230
1283
  function isProcessAlive2(pid) {
@@ -1385,22 +1438,34 @@ var resolveHubUrl = () => process.env.INPLAN_PLUGIN_URL || process.env.INPLAN_CO
1385
1438
  var PLUGIN_HTTP = resolveHubUrl().replace(/^ws/, "http");
1386
1439
  var defaultCacheDir = () => join7(process.env.INPLAN_HOME || join7(homedir5(), ".inplan"), "plugin-cache");
1387
1440
  var defaultDeps = {
1388
- resolve: resolveDesktopPlugin,
1441
+ resolve: resolvePluginOutcome,
1389
1442
  importCli: (p) => import(pathToFileURL(p).href)
1390
1443
  };
1391
- async function loadPluginGate(session, options, deps = defaultDeps) {
1444
+ async function loadPluginGateOutcome(session, options, deps = defaultDeps) {
1392
1445
  try {
1393
- const bundle = await deps.resolve({
1446
+ const { plugin, reason } = await deps.resolve({
1394
1447
  apiBase: options.apiBase ?? PLUGIN_HTTP,
1395
1448
  token: options.token,
1396
1449
  cacheDir: options.cacheDir ?? defaultCacheDir(),
1397
- ...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 } : {}
1398
1455
  });
1399
- const cliName = bundle?.entries.cli;
1400
- const cliPath = cliName ? bundle?.files[cliName] : void 0;
1401
- 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" };
1402
1460
  const cli = await deps.importCli(cliPath);
1403
- 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;
1404
1469
  } catch {
1405
1470
  return null;
1406
1471
  }
@@ -1443,6 +1508,14 @@ function trackGateDegradations(gate, localStore, onWriteError) {
1443
1508
  }
1444
1509
  };
1445
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
+ }
1446
1519
 
1447
1520
  // src/presence.ts
1448
1521
  import { HocuspocusProvider, HocuspocusProviderWebsocket } from "@hocuspocus/provider";
@@ -1472,6 +1545,36 @@ function announcePresence(docId, token, model) {
1472
1545
  }
1473
1546
 
1474
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
+ }
1475
1578
  var defaultActionable = (e) => e.actor === "user";
1476
1579
  function wakePredicate(wake) {
1477
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;
@@ -1481,6 +1584,9 @@ function waitForActions(opts) {
1481
1584
  const pollMs2 = opts.pollMs ?? 200;
1482
1585
  const isActionable = opts.isActionable ?? defaultActionable;
1483
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;
1484
1590
  const ch = opts.channel;
1485
1591
  return new Promise((resolve4, reject) => {
1486
1592
  let deadline = null;
@@ -1488,6 +1594,10 @@ function waitForActions(opts) {
1488
1594
  let sawEditorAlive = false;
1489
1595
  let busy = false;
1490
1596
  let done = false;
1597
+ let failingSince = null;
1598
+ const reads = inFlightGate();
1599
+ const locks = inFlightGate();
1600
+ const presences = inFlightGate();
1491
1601
  const cleanup = () => {
1492
1602
  clearInterval(timer);
1493
1603
  opts.signal?.removeEventListener("abort", onAbort);
@@ -1506,13 +1616,19 @@ function waitForActions(opts) {
1506
1616
  };
1507
1617
  const tick = async () => {
1508
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
+ }
1509
1625
  busy = true;
1510
1626
  try {
1511
- const { entries, cursor } = await ch.readSince(opts.cursor);
1627
+ const { entries, cursor } = await reads.run(() => ch.readSince(opts.cursor), pollTimeoutMs);
1512
1628
  if (done) return;
1513
1629
  if (opts.token) {
1514
1630
  try {
1515
- if (await ch.isSuperseded(opts.token)) {
1631
+ if (!locks.busy() && await locks.run(() => ch.isSuperseded(opts.token), pollTimeoutMs)) {
1516
1632
  finish({ entries, cursor, superseded: true });
1517
1633
  return;
1518
1634
  }
@@ -1520,13 +1636,13 @@ function waitForActions(opts) {
1520
1636
  }
1521
1637
  }
1522
1638
  if (watchEditor) {
1523
- let alive = false;
1639
+ let alive;
1524
1640
  try {
1525
- alive = await ch.presence();
1641
+ if (!presences.busy()) alive = await presences.run(() => ch.presence(), pollTimeoutMs);
1526
1642
  } catch {
1527
1643
  }
1528
- if (alive) sawEditorAlive = true;
1529
- else if (sawEditorAlive) {
1644
+ if (alive === true) sawEditorAlive = true;
1645
+ else if (alive === false && sawEditorAlive) {
1530
1646
  finish({ entries, cursor, editorGone: true });
1531
1647
  return;
1532
1648
  }
@@ -1539,6 +1655,13 @@ function waitForActions(opts) {
1539
1655
  finish({ entries, cursor });
1540
1656
  }
1541
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
+ }
1542
1665
  } finally {
1543
1666
  busy = false;
1544
1667
  }
@@ -1641,6 +1764,9 @@ var VERSION = versionFromModule(import.meta.url);
1641
1764
  function output(obj) {
1642
1765
  process.stdout.write(JSON.stringify(obj) + "\n");
1643
1766
  }
1767
+ function exitAfterFlush(code, out = process.stdout, exit = process.exit, err = process.stderr) {
1768
+ out.write("", () => err.write("", () => exit(code)));
1769
+ }
1644
1770
  function getFlag(args, name) {
1645
1771
  const withEq = args.find((a) => a.startsWith(`--${name}=`));
1646
1772
  if (withEq) return withEq.slice(name.length + 3);
@@ -1848,11 +1974,13 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1848
1974
  message: "Edit removes anchored comment(s). Re-run wait with --confirmed-comment-deletion=<ids> to proceed.",
1849
1975
  lost: ev.unconfirmed.map((c) => ({ id: c.id, text: c.text, author: c.author }))
1850
1976
  });
1851
- process.exit(3);
1977
+ exitAfterFlush(3);
1978
+ return "exiting";
1852
1979
  }
1853
1980
  if (!ev.integrityOk) {
1854
1981
  output({ status: "integrity_error", errors: ev.integrityErrors });
1855
- process.exit(2);
1982
+ exitAfterFlush(2);
1983
+ return "exiting";
1856
1984
  }
1857
1985
  const acceptance = acceptanceFrom(history);
1858
1986
  const quarantine = acceptance === "review" && parse(canonicalText).body !== parse(current).body;
@@ -1869,15 +1997,24 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1869
1997
  const mode = modeFrom(history);
1870
1998
  const isActionable = wakePredicate(mode.wake);
1871
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
+ }
1872
2009
  if (result.superseded) {
1873
2010
  backend.logExit("superseded");
1874
2011
  output({ status: "superseded" });
1875
- return;
2012
+ return "ok";
1876
2013
  }
1877
2014
  if (backend.onSaveLocally && result.entries.some((e) => e.type === LogEventType.SaveLocallyRequested)) {
1878
2015
  backend.logExit("save_locally");
1879
2016
  await backend.onSaveLocally();
1880
- return;
2017
+ return "ok";
1881
2018
  }
1882
2019
  await channel.setCursor(result.cursor);
1883
2020
  const navEntry = result.entries.find((e) => e.type === LogEventType.NavigatedTo);
@@ -1885,7 +2022,7 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1885
2022
  const path = navEntry.payload?.path;
1886
2023
  backend.logExit("navigated");
1887
2024
  output({ status: "navigated", ...path ? { path } : {}, cursor: result.cursor, closed: false });
1888
- return;
2025
+ return "ok";
1889
2026
  }
1890
2027
  const closeEntry = result.entries.find((e) => e.type === LogEventType.SessionClosed);
1891
2028
  let status;
@@ -1915,6 +2052,7 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1915
2052
  closed: status === "closed",
1916
2053
  entries: result.entries
1917
2054
  });
2055
+ return "ok";
1918
2056
  }
1919
2057
  async function doLogin(args) {
1920
2058
  const url = getFlag(args, "url") ?? process.env.INPLAN_SUPABASE_URL;
@@ -1971,6 +2109,37 @@ function defaultBrowserLogin() {
1971
2109
  If it didn't open, paste that URL into your browser.
1972
2110
  `) });
1973
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
+ }
1974
2143
  async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile, model) {
1975
2144
  if (!await ensureLoggedIn(rest)) {
1976
2145
  process.stderr.write("inplan: not logged in (or session expired) \u2014 run `inplan login`\n");
@@ -2007,121 +2176,105 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2007
2176
  output({ status: "messaged" });
2008
2177
  return;
2009
2178
  }
2179
+ await warnIfOutdated(UPDATE_PKG, VERSION, stalenessCache());
2010
2180
  const live = liveRemoteBackend(docId, "cli-agent");
2011
- const onSaveLocally = localFile ? async () => {
2012
- const body = await live.store.loadDoc();
2013
- writeFileSync8(localFile, body);
2014
- writeStatus(docPaths(localFile).statusPath, { location: "local", originalPath: localFile, lastSyncedHash: hashBody(body) });
2015
- const pid = spawnApp(localFile);
2016
- output({ status: "moved_local", path: localFile, reopened: pid !== null });
2017
- } : void 0;
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
+ }
2018
2189
  const presence = announcePresence(docId, backend.token, model);
2019
2190
  try {
2020
- const hubUrl = resolveHubUrl();
2021
- const hubSession = JSON.stringify({ url: hubUrl, docName: docId, token: backend.token });
2022
- const gate = await loadPluginGate(hubSession, { token: backend.token });
2023
- if (gate) {
2024
- const workFile = join9(sidecarRoot(), "remote", `${docId}.plan.md`);
2025
- const pendingPath = `${workFile}.pending`;
2026
- const hashPath = `${workFile}.synced`;
2027
- mkdirSync8(dirname9(workFile), { recursive: true });
2028
- const readIf = (p) => existsSync9(p) ? readFileSync9(p, "utf8") : null;
2029
- const recordSynced = (content) => writeFileSync8(hashPath, hashBody(content));
2030
- let onGate = true;
2031
- let canonical = "";
2032
- try {
2033
- canonical = await gate.readCanonical();
2034
- } catch (e) {
2035
- process.stderr.write(`inplan: live-collab hub unreachable (${String(e)}); using turn-based sync
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)})
2036
2202
  `);
2037
- onGate = false;
2038
- }
2039
- if (onGate) {
2040
- const exists = existsSync9(workFile);
2041
- if (shouldHydrateWorkFile({
2042
- exists,
2043
- pending: existsSync9(pendingPath),
2044
- currentHash: exists ? hashBody(readFileSync9(workFile, "utf8")) : null,
2045
- syncedHash: readIf(hashPath)
2046
- })) {
2047
- writeFileSync8(workFile, canonical);
2048
- recordSynced(canonical);
2049
- }
2050
- const localStore = fsBackend(workFile).store;
2051
- const gateStore = {
2052
- loadDoc: () => localStore.loadDoc(),
2053
- saveDoc: (c) => localStore.saveDoc(c),
2054
- getCanonical: () => localStore.getCanonical(),
2055
- setCanonical: (c) => localStore.setCanonical(c),
2056
- backup: (c, m) => localStore.backup(c, m),
2057
- getProposed: () => live.store.getProposed(),
2058
- setProposed: (c) => live.store.setProposed(c),
2059
- clearProposed: () => live.store.clearProposed()
2060
- };
2061
- const onSaveLocallyGate = localFile ? async () => {
2062
- const body = await gate.readCanonical();
2063
- writeFileSync8(localFile, body);
2064
- writeStatus(docPaths(localFile).statusPath, { location: "local", originalPath: localFile, lastSyncedHash: hashBody(body) });
2065
- const pid = spawnApp(localFile);
2066
- output({ status: "moved_local", path: localFile, reopened: pid !== null });
2067
- } : void 0;
2068
- const tracked = trackGateDegradations(
2069
- gate,
2070
- localStore,
2071
- (m) => process.stderr.write(`inplan: live-collab hub write failed (${m}); kept the edit locally to retry
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
2072
2239
  `)
2073
- );
2074
- process.stderr.write(`inplan: live-collab \u2014 plan at ${workFile}; read/edit it there, then re-run to sync
2240
+ );
2241
+ process.stderr.write(`inplan: live-collab \u2014 plan at ${workFile}; read/edit it there, then re-run to sync
2075
2242
  `);
2076
- await waitCycle(
2077
- {
2078
- channel: live.channel,
2079
- // turns/comments still ride the cloud control log (self-refreshing)…
2080
- store: gateStore,
2081
- // …the agent reads/edits a local working copy; proposals go to the cloud…
2082
- history: async () => (await live.channel.readSince(0)).entries,
2083
- logExit: () => {
2084
- },
2085
- ...onSaveLocallyGate ? { onSaveLocally: onSaveLocallyGate } : {}
2086
- },
2087
- explicitCursor,
2088
- confirmed,
2089
- model,
2090
- tracked.gate
2091
- // …and accepted edits apply through the hub, not the store.
2092
- );
2093
- if (tracked.readFailed() || tracked.writeFailed()) {
2094
- if (pendingRequiresReplay({ readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() })) {
2095
- writeFileSync8(pendingPath, "1");
2096
- }
2097
- process.stderr.write("inplan: hub was unavailable this turn \u2014 keeping local edits (will sync next turn)\n");
2098
- } else {
2099
- if (existsSync9(pendingPath)) rmSync2(pendingPath);
2100
- recordSynced(readFileSync9(workFile, "utf8"));
2101
- try {
2102
- const fresh = await gate.readCanonical();
2103
- writeFileSync8(workFile, fresh);
2104
- recordSynced(fresh);
2105
- } catch {
2106
- }
2107
- }
2108
- return;
2109
- }
2110
- }
2111
- await waitCycle(
2243
+ const outcome = await waitCycle(
2112
2244
  {
2113
2245
  channel: live.channel,
2114
- store: live.store,
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…
2115
2249
  history: async () => (await live.channel.readSince(0)).entries,
2116
2250
  logExit: () => {
2117
2251
  },
2118
- // no local sidecar for a cloud doc
2119
- ...onSaveLocally ? { onSaveLocally } : {}
2252
+ ...onSaveLocallyGate ? { onSaveLocally: onSaveLocallyGate } : {}
2120
2253
  },
2121
2254
  explicitCursor,
2122
2255
  confirmed,
2123
- model
2256
+ model,
2257
+ tracked.gate
2258
+ // …and accepted edits apply through the hub, not the store.
2124
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;
2125
2278
  } finally {
2126
2279
  presence.destroy();
2127
2280
  }
@@ -2157,11 +2310,32 @@ async function doDemote(file, args) {
2157
2310
  process.stderr.write("inplan: not logged in (or session expired) \u2014 run `inplan login`\n");
2158
2311
  process.exit(1);
2159
2312
  }
2160
- 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
+ }
2161
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();
2162
2336
  writeFileSync8(dest, body);
2163
2337
  writeStatus(p.statusPath, { location: "local", originalPath: dest, lastSyncedHash: hashBody(body) });
2164
- output({ status: "demoted", location: "local", path: dest });
2338
+ output({ status: "demoted", location: "local", path: dest, source: choice.use });
2165
2339
  }
2166
2340
  function firstHeading(body) {
2167
2341
  return body.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() || null;
@@ -2735,7 +2909,7 @@ async function main() {
2735
2909
  );
2736
2910
  if (!cmd || !["open", "wait", "signal", "message", "comment", "relay", "status", "promote", "demote", "upload"].includes(cmd)) {
2737
2911
  process.stderr.write(
2738
- '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>\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'
2739
2913
  );
2740
2914
  process.exit(64);
2741
2915
  }
@@ -2899,17 +3073,34 @@ function isProgramEntry() {
2899
3073
  }
2900
3074
  }
2901
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
+ });
2902
3086
  main().catch((err) => {
2903
3087
  process.stderr.write(`inplan: ${err.message}
2904
3088
  `);
2905
- process.exit(1);
3089
+ output({ status: "internal_error", message: err.message });
3090
+ exitAfterFlush(1);
2906
3091
  });
2907
3092
  }
2908
3093
  export {
3094
+ EXIT_PLUGIN_UNAVAILABLE,
3095
+ EXIT_UPGRADE_REQUIRED,
3096
+ EXIT_WAIT_FAILED,
2909
3097
  activeDocForCwd,
2910
3098
  canInteractiveLogin,
2911
3099
  doUpload,
2912
3100
  ensureLoggedIn,
3101
+ exitAfterFlush,
3102
+ explainNoGate,
2913
3103
  notesFromHook,
3104
+ shellQuote,
2914
3105
  transcriptTextBlocks
2915
3106
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inplan",
3
- "version": "0.1.26",
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": {