inplan 0.1.26 → 0.1.28

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.
package/bin/cli.js CHANGED
@@ -4,9 +4,9 @@
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 as renameSync2, rmSync as rmSync2, statSync as statSync3, writeFileSync as writeFileSync8 } from "fs";
8
- import { homedir as homedir6 } from "os";
9
- import { basename as basename3, dirname as dirname9, isAbsolute as isAbsolute2, join as join9, relative as relative4, resolve as resolve3 } from "path";
7
+ import { appendFileSync as appendFileSync2, copyFileSync, existsSync as existsSync10, mkdirSync as mkdirSync9, readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync, renameSync as renameSync2, rmSync as rmSync2, statSync as statSync4, writeFileSync as writeFileSync9 } from "fs";
8
+ import { homedir as homedir7 } from "os";
9
+ import { basename as basename3, dirname as dirname10, isAbsolute as isAbsolute2, join as join10, relative as relative4, resolve as resolve3 } from "path";
10
10
  import { fileURLToPath as fileURLToPath2, pathToFileURL as pathToFileURL2 } from "url";
11
11
 
12
12
  // ../core/dist/chunk-2A42CIA7.js
@@ -512,7 +512,7 @@ function writeStatus(statusPath, status) {
512
512
  writeFileSync4(statusPath, `${JSON.stringify(status, null, 2)}
513
513
  `);
514
514
  }
515
- var PLUGIN_PUBLIC_KEY = process.env.INPLAN_PLUGIN_PUBLIC_KEY ?? "";
515
+ var PLUGIN_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAVP11te5E7xzNJ4reKg0+mAnrr91gcyD1bMr43Homq98=\n-----END PUBLIC KEY-----\n";
516
516
  function verifyLease(token, publicKeyPem = PLUGIN_PUBLIC_KEY, now = Date.now()) {
517
517
  try {
518
518
  if (!publicKeyPem || typeof token !== "string") return null;
@@ -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;
@@ -1032,115 +1054,289 @@ function liveRemoteBackend(docId, consumerId = "cli-agent") {
1032
1054
  }
1033
1055
 
1034
1056
  // src/cliLogin.ts
1035
- import { createServer } from "http";
1036
1057
  import { spawn } from "child_process";
1037
- import { randomBytes } from "crypto";
1058
+ import { webcrypto } from "crypto";
1059
+ import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync7, rmdirSync, statSync as statSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6 } from "fs";
1060
+ import { homedir as homedir5 } from "os";
1061
+ import { dirname as dirname6, join as join7 } from "path";
1062
+
1063
+ // src/pluginGate.ts
1064
+ import { homedir as homedir4 } from "os";
1065
+ import { join as join6 } from "path";
1066
+ import { pathToFileURL } from "url";
1067
+ var DEFAULT_HUB_URL = "wss://inplan-collab.fly.dev";
1068
+ var resolveHubUrl = () => process.env.INPLAN_PLUGIN_URL || process.env.INPLAN_COLLAB_URL || DEFAULT_HUB_URL;
1069
+ var hubHttpBase = () => resolveHubUrl().replace(/^ws/, "http").replace(/\/+$/, "");
1070
+ var PLUGIN_HTTP = hubHttpBase();
1071
+ var defaultCacheDir = () => join6(process.env.INPLAN_HOME || join6(homedir4(), ".inplan"), "plugin-cache");
1072
+ var defaultDeps = {
1073
+ resolve: resolvePluginOutcome,
1074
+ importCli: (p) => import(pathToFileURL(p).href)
1075
+ };
1076
+ async function loadPluginGateOutcome(session, options, deps = defaultDeps) {
1077
+ try {
1078
+ const { plugin, reason } = await deps.resolve({
1079
+ apiBase: options.apiBase ?? PLUGIN_HTTP,
1080
+ token: options.token,
1081
+ cacheDir: options.cacheDir ?? defaultCacheDir(),
1082
+ // Forward whenever DEFINED, not whenever truthy: an explicit `""` means "nothing can be
1083
+ // verified" and must reach the resolver, which then refuses without a network call. Dropping
1084
+ // it would silently substitute the baked-in key and verify against something the caller
1085
+ // deliberately disabled.
1086
+ ...options.publicKey !== void 0 ? { publicKey: options.publicKey } : {}
1087
+ });
1088
+ if (!plugin) return { gate: null, reason };
1089
+ const cliName = plugin.entries.cli;
1090
+ const cliPath = cliName ? plugin.files[cliName] : void 0;
1091
+ if (!cliPath) return { gate: null, reason: "unavailable" };
1092
+ const cli = await deps.importCli(cliPath);
1093
+ return { gate: cli.gate(session), reason: null };
1094
+ } catch {
1095
+ return { gate: null, reason: "unavailable" };
1096
+ }
1097
+ }
1098
+ async function loadPluginGate(session, options, deps = defaultDeps) {
1099
+ try {
1100
+ return (await loadPluginGateOutcome(session, options, deps)).gate;
1101
+ } catch {
1102
+ return null;
1103
+ }
1104
+ }
1105
+
1106
+ // src/cliLogin.ts
1107
+ var subtle = webcrypto.subtle;
1038
1108
  var DEFAULT_WEB_ORIGIN = process.env.INPLAN_WEB_URL || "https://inplan.ai";
1109
+ var HKDF_INFO = "inplan cli-login v1";
1039
1110
  var DEFAULT_TIMEOUT_MS = 3 * 6e4;
1040
- var MAX_BODY_BYTES = 64 * 1024;
1041
- function openInBrowser(url) {
1042
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1043
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
1111
+ var POLL_MS = 2e3;
1112
+ var NUDGE_MS = 3e4;
1113
+ var REQUEST_TIMEOUT_MS = 15e3;
1114
+ function loginApiBase() {
1115
+ return hubHttpBase();
1116
+ }
1117
+ function pendingLoginPath() {
1118
+ const base2 = process.env.INPLAN_HOME || join7(homedir5(), ".inplan");
1119
+ return join7(base2, "login-pending.json");
1120
+ }
1121
+ function clearPendingLogin() {
1044
1122
  try {
1045
- const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
1046
- child.on("error", () => {
1047
- });
1048
- child.unref();
1123
+ unlinkSync2(pendingLoginPath());
1049
1124
  } catch {
1050
1125
  }
1051
1126
  }
1052
- function isHandoff(v) {
1053
- if (typeof v !== "object" || v === null) return false;
1054
- const o = v;
1055
- return typeof o.state === "string" && typeof o.url === "string" && typeof o.anon === "string" && typeof o.refresh === "string" && (o.email === void 0 || typeof o.email === "string");
1127
+ var LOCK_WAIT_MS2 = 2e3;
1128
+ var LOCK_RETRY_MS = 25;
1129
+ var LOCK_STALE_MS2 = 5e3;
1130
+ async function withSidecarLock(fn) {
1131
+ const lock = pendingLoginPath() + ".lock";
1132
+ const deadline = Date.now() + LOCK_WAIT_MS2;
1133
+ for (; ; ) {
1134
+ try {
1135
+ mkdirSync6(lock, { recursive: false });
1136
+ break;
1137
+ } catch (e) {
1138
+ if (e.code !== "EEXIST") throw e;
1139
+ try {
1140
+ if (Date.now() - statSync3(lock).mtimeMs > LOCK_STALE_MS2) rmdirSync(lock);
1141
+ } catch {
1142
+ }
1143
+ if (Date.now() > deadline) throw new Error("could not acquire the login lock \u2014 another inplan process is holding it");
1144
+ await new Promise((r) => setTimeout(r, LOCK_RETRY_MS));
1145
+ }
1146
+ }
1147
+ try {
1148
+ return await fn();
1149
+ } finally {
1150
+ try {
1151
+ rmdirSync(lock);
1152
+ } catch {
1153
+ }
1154
+ }
1155
+ }
1156
+ async function clearPendingLoginFor(sessionId) {
1157
+ await withSidecarLock(() => {
1158
+ const path = pendingLoginPath();
1159
+ try {
1160
+ const p = JSON.parse(readFileSync7(path, "utf8"));
1161
+ if (p.sessionId !== sessionId) return;
1162
+ } catch {
1163
+ }
1164
+ clearPendingLogin();
1165
+ });
1166
+ }
1167
+ function loadPendingLoginLocked(now) {
1168
+ const path = pendingLoginPath();
1169
+ if (!existsSync8(path)) return null;
1170
+ try {
1171
+ const p = JSON.parse(readFileSync7(path, "utf8"));
1172
+ if (typeof p.sessionId !== "string" || typeof p.privateKeyPkcs8 !== "string" || typeof p.pollToken !== "string" || typeof p.url !== "string" || typeof p.apiBase !== "string" || typeof p.expiresAt !== "number" || p.expiresAt <= now) {
1173
+ clearPendingLogin();
1174
+ return null;
1175
+ }
1176
+ return p;
1177
+ } catch {
1178
+ clearPendingLogin();
1179
+ return null;
1180
+ }
1181
+ }
1182
+ function loadPendingLogin(now = Date.now()) {
1183
+ return withSidecarLock(() => loadPendingLoginLocked(now));
1056
1184
  }
1057
- function browserLogin(opts = {}) {
1185
+ async function createLoginSession(opts = {}) {
1186
+ const fetchImpl = opts.fetchImpl ?? fetch;
1187
+ const now = opts.now ?? Date.now;
1188
+ const existing = await loadPendingLogin(now());
1189
+ if (existing) return existing;
1190
+ const apiBase = opts.apiBase ?? loginApiBase();
1058
1191
  const webOrigin = (opts.webOrigin ?? DEFAULT_WEB_ORIGIN).replace(/\/$/, "");
1059
- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1060
- const open = opts.open ?? openInBrowser;
1061
- const state = randomBytes(16).toString("hex");
1062
- return new Promise((resolve4, reject) => {
1063
- let settled = false;
1064
- const finish = (fn) => {
1065
- if (settled) return;
1066
- settled = true;
1067
- clearTimeout(timer);
1068
- server.close();
1069
- fn();
1070
- };
1071
- const cors = (req, res) => {
1072
- res.setHeader("Access-Control-Allow-Origin", req.headers.origin || webOrigin);
1073
- res.setHeader("Vary", "Origin");
1074
- res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
1075
- res.setHeader("Access-Control-Allow-Headers", "content-type");
1076
- };
1077
- const server = createServer((req, res) => {
1078
- const url = req.url ?? "";
1079
- if (req.method === "OPTIONS" && url.startsWith("/cb")) {
1080
- cors(req, res);
1081
- res.writeHead(204).end();
1082
- return;
1083
- }
1084
- if (req.method !== "POST" || !url.startsWith("/cb")) {
1085
- res.writeHead(404).end();
1086
- return;
1087
- }
1088
- cors(req, res);
1089
- let body = "";
1090
- let tooBig = false;
1091
- req.on("data", (chunk) => {
1092
- body += chunk.toString("utf8");
1093
- if (body.length > MAX_BODY_BYTES) {
1094
- tooBig = true;
1095
- req.destroy();
1096
- }
1192
+ const keys = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]);
1193
+ const pub = Buffer.from(await subtle.exportKey("spki", keys.publicKey)).toString("base64");
1194
+ const priv = Buffer.from(await subtle.exportKey("pkcs8", keys.privateKey)).toString("base64");
1195
+ const res = await fetchImpl(`${apiBase}/api/v1/cli-login`, { method: "POST", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
1196
+ if (!res.ok) throw new Error(`could not start a sign-in session (HTTP ${res.status})`);
1197
+ const { sessionId, pollToken, expiresInSec } = await res.json();
1198
+ if (typeof sessionId !== "string" || !sessionId || typeof pollToken !== "string" || !pollToken) {
1199
+ throw new Error("could not start a sign-in session (bad response)");
1200
+ }
1201
+ const pending = {
1202
+ sessionId,
1203
+ privateKeyPkcs8: priv,
1204
+ pollToken,
1205
+ // `pub` rides the URL FRAGMENT so it never reaches server access logs (a log reader holding
1206
+ // session + pub could complete the session for their own account); the page reads it from
1207
+ // location.hash. Public key or not, keep the whole capability out of logs.
1208
+ url: `${webOrigin}/cli-auth?session=${encodeURIComponent(sessionId)}#pub=${encodeURIComponent(pub)}`,
1209
+ apiBase,
1210
+ // Guard against a bogus server TTL: NaN/Infinity/negative would make expiresAt a past
1211
+ // timestamp — or one that NEVER expires (NaN compares false forever), leaving a dead sidecar
1212
+ // that every later invocation resumes until the server 404s.
1213
+ expiresAt: now() + (Number.isFinite(expiresInSec) && expiresInSec > 0 ? expiresInSec : 600) * 1e3
1214
+ };
1215
+ const path = pendingLoginPath();
1216
+ mkdirSync6(dirname6(path), { recursive: true });
1217
+ return withSidecarLock(() => {
1218
+ const winner = loadPendingLoginLocked(now());
1219
+ if (winner) return winner;
1220
+ writeFileSync6(path, JSON.stringify(pending, null, 2), { mode: 384 });
1221
+ chmodSync2(path, 384);
1222
+ return pending;
1223
+ });
1224
+ }
1225
+ var LoginSessionExpiredError = class extends Error {
1226
+ };
1227
+ async function pollLoginSession(pending, opts = {}) {
1228
+ const fetchImpl = opts.fetchImpl ?? fetch;
1229
+ const now = opts.now ?? Date.now;
1230
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1231
+ const deadline = now() + (opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1232
+ const nudgeAt = now() + NUDGE_MS;
1233
+ let nudged = false;
1234
+ let sawOpened = false;
1235
+ while (true) {
1236
+ if (!nudged && !sawOpened && now() >= nudgeAt) {
1237
+ nudged = true;
1238
+ opts.onNudge?.();
1239
+ }
1240
+ if (now() >= pending.expiresAt) {
1241
+ await clearPendingLoginFor(pending.sessionId);
1242
+ throw new LoginSessionExpiredError("the sign-in link expired \u2014 run the command again for a fresh one");
1243
+ }
1244
+ if (now() >= deadline) throw new Error("login timed out \u2014 no response from the browser");
1245
+ let res;
1246
+ try {
1247
+ res = await fetchImpl(`${pending.apiBase}/api/v1/cli-login/${encodeURIComponent(pending.sessionId)}`, {
1248
+ method: "GET",
1249
+ // The poll credential rides a header (never a URL, so never an access log) — see
1250
+ // PendingLogin.pollToken: the session id alone must not read or destroy the handoff.
1251
+ headers: { "x-inplan-poll-token": pending.pollToken },
1252
+ // Capped to the REMAINING deadline: an in-flight request must not let the foreground
1253
+ // wait overrun its budget by a whole request-timeout.
1254
+ signal: AbortSignal.timeout(Math.max(1, Math.min(REQUEST_TIMEOUT_MS, deadline - now())))
1097
1255
  });
1098
- req.on("end", () => {
1099
- if (tooBig) {
1100
- res.writeHead(413).end();
1101
- return;
1102
- }
1103
- let parsed;
1256
+ } catch {
1257
+ await sleep(POLL_MS);
1258
+ continue;
1259
+ }
1260
+ if (res.status === 404) {
1261
+ await clearPendingLoginFor(pending.sessionId);
1262
+ throw new LoginSessionExpiredError("the sign-in link expired \u2014 run the command again for a fresh one");
1263
+ }
1264
+ if (res.ok) {
1265
+ let body;
1266
+ try {
1267
+ body = await res.json();
1268
+ } catch {
1269
+ await sleep(POLL_MS);
1270
+ continue;
1271
+ }
1272
+ if (body.status === "completed" && body.epk && body.iv && body.ct) {
1273
+ let auth;
1104
1274
  try {
1105
- parsed = JSON.parse(body);
1275
+ auth = await unsealHandoff(pending.privateKeyPkcs8, { epk: body.epk, iv: body.iv, ct: body.ct });
1106
1276
  } catch {
1107
- res.writeHead(400).end();
1108
- return;
1109
- }
1110
- if (!isHandoff(parsed) || parsed.state !== state) {
1111
- res.writeHead(403).end();
1112
- return;
1277
+ await clearPendingLoginFor(pending.sessionId);
1278
+ throw new LoginSessionExpiredError("the sign-in handoff could not be read \u2014 run the command again for a fresh link");
1113
1279
  }
1114
- res.writeHead(200, { "content-type": "text/plain" }).end("inplan: signed in \u2014 you can close this tab.");
1115
- const { url: projUrl, anon, refresh, email } = parsed;
1116
- finish(() => resolve4({ url: projUrl, anonKey: anon, refreshToken: refresh, ...email ? { email } : {} }));
1117
- });
1118
- });
1119
- server.on("error", (err) => finish(() => reject(err)));
1120
- const timer = setTimeout(() => finish(() => reject(new Error("login timed out \u2014 no response from the browser"))), timeoutMs);
1121
- if (typeof timer.unref === "function") timer.unref();
1122
- server.listen(0, "127.0.0.1", () => {
1123
- const { port } = server.address();
1124
- const target = `${webOrigin}/cli-auth?port=${port}&state=${state}`;
1125
- opts.onUrl?.(target);
1126
- open(target);
1280
+ await clearPendingLoginFor(pending.sessionId);
1281
+ return auth;
1282
+ }
1283
+ if (body.status === "opened" || body.status === "completed") sawOpened = true;
1284
+ }
1285
+ await sleep(POLL_MS);
1286
+ }
1287
+ }
1288
+ async function rendezvousLogin(opts = {}) {
1289
+ const pending = await createLoginSession(opts);
1290
+ opts.onUrl?.(pending.url);
1291
+ (opts.open ?? openInBrowser)(pending.url);
1292
+ return pollLoginSession(pending, opts);
1293
+ }
1294
+ function openInBrowser(url) {
1295
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1296
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
1297
+ try {
1298
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
1299
+ child.on("error", () => {
1127
1300
  });
1128
- });
1301
+ child.unref();
1302
+ } catch {
1303
+ }
1304
+ }
1305
+ async function unsealHandoff(privateKeyPkcs8, sealed) {
1306
+ const privateKey = await subtle.importKey("pkcs8", Buffer.from(privateKeyPkcs8, "base64"), { name: "ECDH", namedCurve: "P-256" }, false, [
1307
+ "deriveBits"
1308
+ ]);
1309
+ const epk = await subtle.importKey("spki", Buffer.from(sealed.epk, "base64"), { name: "ECDH", namedCurve: "P-256" }, false, []);
1310
+ const shared = await subtle.deriveBits({ name: "ECDH", public: epk }, privateKey, 256);
1311
+ const hkdfKey = await subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
1312
+ const aes = await subtle.deriveKey(
1313
+ { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: new TextEncoder().encode(HKDF_INFO) },
1314
+ hkdfKey,
1315
+ { name: "AES-GCM", length: 256 },
1316
+ false,
1317
+ ["decrypt"]
1318
+ );
1319
+ const pt = await subtle.decrypt({ name: "AES-GCM", iv: Buffer.from(sealed.iv, "base64") }, aes, Buffer.from(sealed.ct, "base64"));
1320
+ const parsed = JSON.parse(new TextDecoder().decode(pt));
1321
+ if (typeof parsed.url !== "string" || typeof parsed.anon !== "string" || typeof parsed.refresh !== "string") {
1322
+ throw new Error("sign-in handoff was malformed");
1323
+ }
1324
+ return { url: parsed.url, anonKey: parsed.anon, refreshToken: parsed.refresh, ...parsed.email ? { email: parsed.email } : {} };
1129
1325
  }
1130
1326
 
1131
1327
  // src/cliProfile.ts
1132
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "fs";
1133
- import { homedir as homedir4 } from "os";
1134
- import { dirname as dirname6, join as join6 } from "path";
1328
+ import { existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync7 } from "fs";
1329
+ import { homedir as homedir6 } from "os";
1330
+ import { dirname as dirname7, join as join8 } from "path";
1135
1331
  function profilePath() {
1136
- const base2 = process.env.INPLAN_HOME || join6(homedir4(), ".inplan");
1137
- return join6(base2, "profile.json");
1332
+ const base2 = process.env.INPLAN_HOME || join8(homedir6(), ".inplan");
1333
+ return join8(base2, "profile.json");
1138
1334
  }
1139
1335
  function readLocalProfile() {
1140
1336
  const p = profilePath();
1141
- if (!existsSync8(p)) return null;
1337
+ if (!existsSync9(p)) return null;
1142
1338
  try {
1143
- const raw = JSON.parse(readFileSync7(p, "utf8"));
1339
+ const raw = JSON.parse(readFileSync8(p, "utf8"));
1144
1340
  if (typeof raw.name !== "string" || raw.name.trim() === "") return null;
1145
1341
  const source = raw.source === "cloud" || raw.source === "git" ? raw.source : "manual";
1146
1342
  return { name: raw.name.trim(), ...raw.email ? { email: raw.email } : {}, source };
@@ -1150,8 +1346,8 @@ function readLocalProfile() {
1150
1346
  }
1151
1347
  function writeLocalProfile(p) {
1152
1348
  const path = profilePath();
1153
- mkdirSync6(dirname6(path), { recursive: true });
1154
- writeFileSync6(path, `${JSON.stringify(p, null, 2)}
1349
+ mkdirSync7(dirname7(path), { recursive: true });
1350
+ writeFileSync7(path, `${JSON.stringify(p, null, 2)}
1155
1351
  `);
1156
1352
  }
1157
1353
  function setManualProfile(name, email) {
@@ -1176,7 +1372,7 @@ async function resolveIdentity(file) {
1176
1372
  }
1177
1373
  }
1178
1374
  if (file) {
1179
- const git = gitIdentity(dirname6(file));
1375
+ const git = gitIdentity(dirname7(file));
1180
1376
  if (git) {
1181
1377
  const prof = fromParts(git, "git");
1182
1378
  if (prof) {
@@ -1201,9 +1397,13 @@ function compareVersions(a, b) {
1201
1397
  }
1202
1398
  return 0;
1203
1399
  }
1400
+ var REGISTRY_TIMEOUT_MS = 3e3;
1204
1401
  async function latestVersion(pkg) {
1205
1402
  try {
1206
- const res = await fetch(`https://registry.npmjs.org/${pkg.replace("/", "%2F")}/latest`, { headers: { accept: "application/json" } });
1403
+ const res = await fetch(`https://registry.npmjs.org/${pkg.replace("/", "%2F")}/latest`, {
1404
+ headers: { accept: "application/json" },
1405
+ signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS)
1406
+ });
1207
1407
  if (!res.ok) return null;
1208
1408
  const data = await res.json();
1209
1409
  return typeof data.version === "string" ? data.version : null;
@@ -1225,6 +1425,33 @@ function selfUpdate(pkg) {
1225
1425
  child.on("close", (code) => resolve4({ ok: code === 0, output: output2.trim() }));
1226
1426
  });
1227
1427
  }
1428
+ var STALENESS_TTL_MS = 6 * 60 * 60 * 1e3;
1429
+ async function warnIfOutdated(pkg, current, deps = {}) {
1430
+ const now = (deps.now ?? Date.now)();
1431
+ try {
1432
+ const cached = deps.readCache?.() ?? null;
1433
+ if (cached) {
1434
+ const { at, latest: latest2, pkg: cachedPkg } = JSON.parse(cached);
1435
+ if (typeof at === "number" && typeof latest2 === "string" && cachedPkg === pkg && at <= now && now - at < STALENESS_TTL_MS) {
1436
+ return compareVersions(current, latest2) < 0 ? emitOutdated(pkg, current, latest2) : null;
1437
+ }
1438
+ }
1439
+ } catch {
1440
+ }
1441
+ const latest = await (deps.fetchLatest ?? latestVersion)(pkg);
1442
+ if (latest === null) return null;
1443
+ try {
1444
+ deps.writeCache?.(JSON.stringify({ at: now, latest, pkg }));
1445
+ } catch {
1446
+ }
1447
+ return compareVersions(current, latest) < 0 ? emitOutdated(pkg, current, latest) : null;
1448
+ }
1449
+ function emitOutdated(pkg, current, latest) {
1450
+ 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\`.`;
1451
+ process.stderr.write(`${msg}
1452
+ `);
1453
+ return msg;
1454
+ }
1228
1455
 
1229
1456
  // src/editorProcess.ts
1230
1457
  function isProcessAlive2(pid) {
@@ -1376,36 +1603,6 @@ function addComment(currentText, input) {
1376
1603
  return { text: serialize(next), comment };
1377
1604
  }
1378
1605
 
1379
- // src/pluginGate.ts
1380
- import { homedir as homedir5 } from "os";
1381
- import { join as join7 } from "path";
1382
- import { pathToFileURL } from "url";
1383
- var DEFAULT_HUB_URL = "wss://inplan-collab.fly.dev";
1384
- var resolveHubUrl = () => process.env.INPLAN_PLUGIN_URL || process.env.INPLAN_COLLAB_URL || DEFAULT_HUB_URL;
1385
- var PLUGIN_HTTP = resolveHubUrl().replace(/^ws/, "http");
1386
- var defaultCacheDir = () => join7(process.env.INPLAN_HOME || join7(homedir5(), ".inplan"), "plugin-cache");
1387
- var defaultDeps = {
1388
- resolve: resolveDesktopPlugin,
1389
- importCli: (p) => import(pathToFileURL(p).href)
1390
- };
1391
- async function loadPluginGate(session, options, deps = defaultDeps) {
1392
- try {
1393
- const bundle = await deps.resolve({
1394
- apiBase: options.apiBase ?? PLUGIN_HTTP,
1395
- token: options.token,
1396
- cacheDir: options.cacheDir ?? defaultCacheDir(),
1397
- ...options.publicKey ? { publicKey: options.publicKey } : {}
1398
- });
1399
- const cliName = bundle?.entries.cli;
1400
- const cliPath = cliName ? bundle?.files[cliName] : void 0;
1401
- if (!cliPath) return null;
1402
- const cli = await deps.importCli(cliPath);
1403
- return cli.gate(session);
1404
- } catch {
1405
- return null;
1406
- }
1407
- }
1408
-
1409
1606
  // src/liveSync.ts
1410
1607
  function shouldHydrateWorkFile(o) {
1411
1608
  if (!o.exists) return true;
@@ -1443,6 +1640,14 @@ function trackGateDegradations(gate, localStore, onWriteError) {
1443
1640
  }
1444
1641
  };
1445
1642
  }
1643
+ function postTurnAction(outcome, degraded) {
1644
+ if (outcome === "exiting") return "stop";
1645
+ return degraded.readFailed || degraded.writeFailed ? "keep-local" : "resync";
1646
+ }
1647
+ function demoteSource({ hubReadable, fromStore }) {
1648
+ if (hubReadable) return { use: "hub" };
1649
+ return fromStore ? { use: "store" } : { use: "abort", reason: "hub_unreadable" };
1650
+ }
1446
1651
 
1447
1652
  // src/presence.ts
1448
1653
  import { HocuspocusProvider, HocuspocusProviderWebsocket } from "@hocuspocus/provider";
@@ -1472,6 +1677,36 @@ function announcePresence(docId, token, model) {
1472
1677
  }
1473
1678
 
1474
1679
  // src/wait.ts
1680
+ var DEFAULT_ERROR_GRACE_MS = 5 * 6e4;
1681
+ var DEFAULT_POLL_TIMEOUT_MS = 3e4;
1682
+ function inFlightGate() {
1683
+ let pending = 0;
1684
+ return {
1685
+ busy: () => pending > 0,
1686
+ run: (start, ms) => {
1687
+ pending += 1;
1688
+ const underlying = start();
1689
+ void underlying.then(
1690
+ () => pending -= 1,
1691
+ () => pending -= 1
1692
+ );
1693
+ return withTimeout(underlying, ms);
1694
+ }
1695
+ };
1696
+ }
1697
+ async function withTimeout(p, ms) {
1698
+ let timer;
1699
+ try {
1700
+ return await Promise.race([
1701
+ p,
1702
+ new Promise((_res, rej) => {
1703
+ timer = setTimeout(() => rej(new Error(`poll timed out after ${ms}ms`)), ms);
1704
+ })
1705
+ ]);
1706
+ } finally {
1707
+ if (timer) clearTimeout(timer);
1708
+ }
1709
+ }
1475
1710
  var defaultActionable = (e) => e.actor === "user";
1476
1711
  function wakePredicate(wake) {
1477
1712
  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 +1716,9 @@ function waitForActions(opts) {
1481
1716
  const pollMs2 = opts.pollMs ?? 200;
1482
1717
  const isActionable = opts.isActionable ?? defaultActionable;
1483
1718
  const watchEditor = opts.watchEditor ?? true;
1719
+ const errorGraceMs = opts.errorGraceMs ?? DEFAULT_ERROR_GRACE_MS;
1720
+ const pollTimeoutMs = opts.pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS;
1721
+ const now = opts.now ?? Date.now;
1484
1722
  const ch = opts.channel;
1485
1723
  return new Promise((resolve4, reject) => {
1486
1724
  let deadline = null;
@@ -1488,6 +1726,10 @@ function waitForActions(opts) {
1488
1726
  let sawEditorAlive = false;
1489
1727
  let busy = false;
1490
1728
  let done = false;
1729
+ let failingSince = null;
1730
+ const reads = inFlightGate();
1731
+ const locks = inFlightGate();
1732
+ const presences = inFlightGate();
1491
1733
  const cleanup = () => {
1492
1734
  clearInterval(timer);
1493
1735
  opts.signal?.removeEventListener("abort", onAbort);
@@ -1506,13 +1748,19 @@ function waitForActions(opts) {
1506
1748
  };
1507
1749
  const tick = async () => {
1508
1750
  if (busy || done) return;
1751
+ if (reads.busy()) {
1752
+ const at = now();
1753
+ failingSince ??= at;
1754
+ if (at - failingSince >= errorGraceMs) finish({ entries: [], cursor: opts.cursor, failed: new Error("polls timed out and are still in flight") });
1755
+ return;
1756
+ }
1509
1757
  busy = true;
1510
1758
  try {
1511
- const { entries, cursor } = await ch.readSince(opts.cursor);
1759
+ const { entries, cursor } = await reads.run(() => ch.readSince(opts.cursor), pollTimeoutMs);
1512
1760
  if (done) return;
1513
1761
  if (opts.token) {
1514
1762
  try {
1515
- if (await ch.isSuperseded(opts.token)) {
1763
+ if (!locks.busy() && await locks.run(() => ch.isSuperseded(opts.token), pollTimeoutMs)) {
1516
1764
  finish({ entries, cursor, superseded: true });
1517
1765
  return;
1518
1766
  }
@@ -1520,13 +1768,13 @@ function waitForActions(opts) {
1520
1768
  }
1521
1769
  }
1522
1770
  if (watchEditor) {
1523
- let alive = false;
1771
+ let alive;
1524
1772
  try {
1525
- alive = await ch.presence();
1773
+ if (!presences.busy()) alive = await presences.run(() => ch.presence(), pollTimeoutMs);
1526
1774
  } catch {
1527
1775
  }
1528
- if (alive) sawEditorAlive = true;
1529
- else if (sawEditorAlive) {
1776
+ if (alive === true) sawEditorAlive = true;
1777
+ else if (alive === false && sawEditorAlive) {
1530
1778
  finish({ entries, cursor, editorGone: true });
1531
1779
  return;
1532
1780
  }
@@ -1539,6 +1787,13 @@ function waitForActions(opts) {
1539
1787
  finish({ entries, cursor });
1540
1788
  }
1541
1789
  }
1790
+ failingSince = null;
1791
+ } catch (e) {
1792
+ const at = now();
1793
+ failingSince ??= at;
1794
+ if (at - failingSince >= errorGraceMs) {
1795
+ finish({ entries: [], cursor: opts.cursor, failed: e instanceof Error ? e : new Error(String(e)) });
1796
+ }
1542
1797
  } finally {
1543
1798
  busy = false;
1544
1799
  }
@@ -1550,19 +1805,19 @@ function waitForActions(opts) {
1550
1805
  }
1551
1806
 
1552
1807
  // src/version.ts
1553
- import { readFileSync as readFileSync8 } from "fs";
1554
- import { dirname as dirname7, join as join8 } from "path";
1808
+ import { readFileSync as readFileSync9 } from "fs";
1809
+ import { dirname as dirname8, join as join9 } from "path";
1555
1810
  import { fileURLToPath } from "url";
1556
1811
  function versionFromDir(moduleDir) {
1557
1812
  try {
1558
- const pkg = JSON.parse(readFileSync8(join8(moduleDir, "..", "package.json"), "utf8"));
1813
+ const pkg = JSON.parse(readFileSync9(join9(moduleDir, "..", "package.json"), "utf8"));
1559
1814
  return typeof pkg.version === "string" ? pkg.version : "0.0.0";
1560
1815
  } catch {
1561
1816
  return "0.0.0";
1562
1817
  }
1563
1818
  }
1564
1819
  function versionFromModule(moduleUrl) {
1565
- return versionFromDir(dirname7(fileURLToPath(moduleUrl)));
1820
+ return versionFromDir(dirname8(fileURLToPath(moduleUrl)));
1566
1821
  }
1567
1822
 
1568
1823
  // src/relayActivity.ts
@@ -1583,12 +1838,12 @@ function toolActivityText(toolName, toolInput) {
1583
1838
  }
1584
1839
 
1585
1840
  // src/ensureDoc.ts
1586
- import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "fs";
1587
- import { dirname as dirname8 } from "path";
1841
+ import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync8 } from "fs";
1842
+ import { dirname as dirname9 } from "path";
1588
1843
  function ensureDocFile(file) {
1589
- mkdirSync7(dirname8(file), { recursive: true });
1844
+ mkdirSync8(dirname9(file), { recursive: true });
1590
1845
  try {
1591
- writeFileSync7(file, "", { flag: "wx" });
1846
+ writeFileSync8(file, "", { flag: "wx" });
1592
1847
  return true;
1593
1848
  } catch (err) {
1594
1849
  if (err.code === "EEXIST") return false;
@@ -1641,6 +1896,9 @@ var VERSION = versionFromModule(import.meta.url);
1641
1896
  function output(obj) {
1642
1897
  process.stdout.write(JSON.stringify(obj) + "\n");
1643
1898
  }
1899
+ function exitAfterFlush(code, out = process.stdout, exit = process.exit, err = process.stderr) {
1900
+ out.write("", () => err.write("", () => exit(code)));
1901
+ }
1644
1902
  function getFlag(args, name) {
1645
1903
  const withEq = args.find((a) => a.startsWith(`--${name}=`));
1646
1904
  if (withEq) return withEq.slice(name.length + 3);
@@ -1655,18 +1913,18 @@ var debounceMs = Number(process.env.INPLAN_DEBOUNCE_MS ?? 3e3);
1655
1913
  var pollMs = Number(process.env.INPLAN_POLL_MS ?? 200);
1656
1914
  function electronDistRel(platform) {
1657
1915
  if (platform === "win32") return "electron.exe";
1658
- if (platform === "darwin") return join9("Electron.app", "Contents", "MacOS", "Electron");
1916
+ if (platform === "darwin") return join10("Electron.app", "Contents", "MacOS", "Electron");
1659
1917
  return "electron";
1660
1918
  }
1661
1919
  function electronBinaryFromDisk(reqUrl) {
1662
1920
  try {
1663
- const pkgDir = dirname9(createRequire(reqUrl).resolve("electron/package.json"));
1921
+ const pkgDir = dirname10(createRequire(reqUrl).resolve("electron/package.json"));
1664
1922
  const rel = electronDistRel(process.platform);
1665
- const bin = join9(pkgDir, "dist", rel);
1666
- if (!existsSync9(bin)) return null;
1923
+ const bin = join10(pkgDir, "dist", rel);
1924
+ if (!existsSync10(bin)) return null;
1667
1925
  try {
1668
- const pathFile = join9(pkgDir, "path.txt");
1669
- if (!existsSync9(pathFile)) writeFileSync8(pathFile, rel);
1926
+ const pathFile = join10(pkgDir, "path.txt");
1927
+ if (!existsSync10(pathFile)) writeFileSync9(pathFile, rel);
1670
1928
  } catch {
1671
1929
  }
1672
1930
  return bin;
@@ -1675,9 +1933,9 @@ function electronBinaryFromDisk(reqUrl) {
1675
1933
  }
1676
1934
  }
1677
1935
  function electronCacheDir() {
1678
- if (process.platform === "win32") return join9(process.env.LOCALAPPDATA ?? join9(homedir6(), "AppData", "Local"), "electron", "Cache");
1679
- if (process.platform === "darwin") return join9(homedir6(), "Library", "Caches", "electron");
1680
- return join9(process.env.XDG_CACHE_HOME ?? join9(homedir6(), ".cache"), "electron");
1936
+ if (process.platform === "win32") return join10(process.env.LOCALAPPDATA ?? join10(homedir7(), "AppData", "Local"), "electron", "Cache");
1937
+ if (process.platform === "darwin") return join10(homedir7(), "Library", "Caches", "electron");
1938
+ return join10(process.env.XDG_CACHE_HOME ?? join10(homedir7(), ".cache"), "electron");
1681
1939
  }
1682
1940
  function cachedElectronZip(version, platform, arch) {
1683
1941
  const root = electronCacheDir();
@@ -1685,9 +1943,9 @@ function cachedElectronZip(version, platform, arch) {
1685
1943
  try {
1686
1944
  let best = null;
1687
1945
  for (const sub of readdirSync2(root)) {
1688
- const f = join9(root, sub, want);
1689
- if (!existsSync9(f)) continue;
1690
- const mtime = statSync3(f).mtimeMs;
1946
+ const f = join10(root, sub, want);
1947
+ if (!existsSync10(f)) continue;
1948
+ const mtime = statSync4(f).mtimeMs;
1691
1949
  if (!best || mtime > best.mtime) best = { file: f, mtime };
1692
1950
  }
1693
1951
  return best?.file ?? null;
@@ -1706,17 +1964,17 @@ function expandArchiveWindows(zipPath, destDir) {
1706
1964
  function autoInstallElectron(reqUrl) {
1707
1965
  if (process.env.INPLAN_NO_ELECTRON_DOWNLOAD === "1") return false;
1708
1966
  try {
1709
- const pkgDir = dirname9(createRequire(reqUrl).resolve("electron/package.json"));
1710
- const installJs = join9(pkgDir, "install.js");
1711
- if (!existsSync9(installJs)) return false;
1967
+ const pkgDir = dirname10(createRequire(reqUrl).resolve("electron/package.json"));
1968
+ const installJs = join10(pkgDir, "install.js");
1969
+ if (!existsSync10(installJs)) return false;
1712
1970
  process.stderr.write("[inplan] editor runtime missing \u2014 retrying the download \u2026\n");
1713
1971
  execFileSync2(process.execPath, [installJs], { cwd: pkgDir, stdio: "inherit", env: process.env });
1714
1972
  if (electronBinaryFromDisk(reqUrl) !== null) return true;
1715
1973
  if (process.platform === "win32") {
1716
- const { version } = JSON.parse(readFileSync9(join9(pkgDir, "package.json"), "utf8"));
1974
+ const { version } = JSON.parse(readFileSync10(join10(pkgDir, "package.json"), "utf8"));
1717
1975
  const zip = cachedElectronZip(version, "win32", process.env.npm_config_arch || process.arch);
1718
- if (zip && expandArchiveWindows(zip, join9(pkgDir, "dist"))) {
1719
- writeFileSync8(join9(pkgDir, "path.txt"), "electron.exe");
1976
+ if (zip && expandArchiveWindows(zip, join10(pkgDir, "dist"))) {
1977
+ writeFileSync9(join10(pkgDir, "path.txt"), "electron.exe");
1720
1978
  }
1721
1979
  }
1722
1980
  return electronBinaryFromDisk(reqUrl) !== null;
@@ -1725,12 +1983,12 @@ function autoInstallElectron(reqUrl) {
1725
1983
  }
1726
1984
  }
1727
1985
  function resolveBundledApp() {
1728
- const here = dirname9(fileURLToPath2(import.meta.url));
1729
- const appMain = join9(here, "..", "app", "main", "index.cjs");
1730
- if (!existsSync9(appMain)) return { appMain: null };
1986
+ const here = dirname10(fileURLToPath2(import.meta.url));
1987
+ const appMain = join10(here, "..", "app", "main", "index.cjs");
1988
+ if (!existsSync10(appMain)) return { appMain: null };
1731
1989
  try {
1732
1990
  const electron = createRequire(import.meta.url)("electron");
1733
- if (typeof electron === "string" && electron && existsSync9(electron)) return { electron, appMain };
1991
+ if (typeof electron === "string" && electron && existsSync10(electron)) return { electron, appMain };
1734
1992
  } catch {
1735
1993
  }
1736
1994
  const onDisk = electronBinaryFromDisk(import.meta.url);
@@ -1765,7 +2023,7 @@ function spawnApp(file) {
1765
2023
  process.stderr.write("[inplan] no bundled editor (running from source?) \u2014 set INPLAN_APP_CMD to your editor; running headless\n");
1766
2024
  } else {
1767
2025
  trackCli("editor_launch_failed", telemetryOn, { reason: "electron_unavailable" });
1768
- const root = resolve3(dirname9(bundled.appMain), "..", "..");
2026
+ const root = resolve3(dirname10(bundled.appMain), "..", "..");
1769
2027
  process.stderr.write(
1770
2028
  `[inplan] the bundled editor's Electron runtime is unavailable: ${bundled.error}
1771
2029
  \u2192 re-download the binary: npm rebuild electron --prefix "${root}"
@@ -1803,7 +2061,7 @@ function maxSeqFrom(entries) {
1803
2061
  }
1804
2062
  function fsBackend(file) {
1805
2063
  const p = docPaths(file);
1806
- mkdirSync8(p.controlDir, { recursive: true });
2064
+ mkdirSync9(p.controlDir, { recursive: true });
1807
2065
  return {
1808
2066
  channel: new FsControlChannel(p),
1809
2067
  store: new FsDocumentStore(p),
@@ -1848,11 +2106,13 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1848
2106
  message: "Edit removes anchored comment(s). Re-run wait with --confirmed-comment-deletion=<ids> to proceed.",
1849
2107
  lost: ev.unconfirmed.map((c) => ({ id: c.id, text: c.text, author: c.author }))
1850
2108
  });
1851
- process.exit(3);
2109
+ exitAfterFlush(3);
2110
+ return "exiting";
1852
2111
  }
1853
2112
  if (!ev.integrityOk) {
1854
2113
  output({ status: "integrity_error", errors: ev.integrityErrors });
1855
- process.exit(2);
2114
+ exitAfterFlush(2);
2115
+ return "exiting";
1856
2116
  }
1857
2117
  const acceptance = acceptanceFrom(history);
1858
2118
  const quarantine = acceptance === "review" && parse(canonicalText).body !== parse(current).body;
@@ -1869,15 +2129,24 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1869
2129
  const mode = modeFrom(history);
1870
2130
  const isActionable = wakePredicate(mode.wake);
1871
2131
  const result = await waitForActions({ channel, cursor, debounceMs, pollMs, isActionable, token: lockToken });
2132
+ if (result.failed) {
2133
+ backend.logExit("poll_failed");
2134
+ process.stderr.write(`inplan: lost contact with the document (${result.failed.message}).
2135
+ If your session expired, run \`inplan login\` and re-attach.
2136
+ `);
2137
+ output({ status: "wait_failed", message: result.failed.message });
2138
+ exitAfterFlush(EXIT_WAIT_FAILED);
2139
+ return "exiting";
2140
+ }
1872
2141
  if (result.superseded) {
1873
2142
  backend.logExit("superseded");
1874
2143
  output({ status: "superseded" });
1875
- return;
2144
+ return "ok";
1876
2145
  }
1877
2146
  if (backend.onSaveLocally && result.entries.some((e) => e.type === LogEventType.SaveLocallyRequested)) {
1878
2147
  backend.logExit("save_locally");
1879
2148
  await backend.onSaveLocally();
1880
- return;
2149
+ return "ok";
1881
2150
  }
1882
2151
  await channel.setCursor(result.cursor);
1883
2152
  const navEntry = result.entries.find((e) => e.type === LogEventType.NavigatedTo);
@@ -1885,7 +2154,7 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1885
2154
  const path = navEntry.payload?.path;
1886
2155
  backend.logExit("navigated");
1887
2156
  output({ status: "navigated", ...path ? { path } : {}, cursor: result.cursor, closed: false });
1888
- return;
2157
+ return "ok";
1889
2158
  }
1890
2159
  const closeEntry = result.entries.find((e) => e.type === LogEventType.SessionClosed);
1891
2160
  let status;
@@ -1915,6 +2184,7 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1915
2184
  closed: status === "closed",
1916
2185
  entries: result.entries
1917
2186
  });
2187
+ return "ok";
1918
2188
  }
1919
2189
  async function doLogin(args) {
1920
2190
  const url = getFlag(args, "url") ?? process.env.INPLAN_SUPABASE_URL;
@@ -1927,8 +2197,45 @@ async function doLogin(args) {
1927
2197
  output({ status: "logged_in", url, ...email ? { email } : {} });
1928
2198
  return;
1929
2199
  }
2200
+ if (loginOptOut(args)) {
2201
+ process.stderr.write("inplan login: non-interactive environment \u2014 pass --url/--anon/--refresh (or the matching INPLAN_* env vars).\n");
2202
+ process.exit(1);
2203
+ }
2204
+ const noBrowserHuman = !canInteractiveLogin(args) && Boolean(process.env.INPLAN_NO_BROWSER) && Boolean(process.stdin.isTTY && process.stdout.isTTY) && !process.env.CI && !isKnownAgentEnv();
2205
+ if (!canInteractiveLogin(args) && !noBrowserHuman || isKnownAgentEnv()) {
2206
+ const pending = await loadPendingLogin();
2207
+ if (pending) {
2208
+ try {
2209
+ process.stderr.write(`inplan: waiting for the pending browser sign-in to finish\u2026
2210
+ ${pending.url}
2211
+ `);
2212
+ const auth = await pollLoginSession(pending, { onNudge: printLoginNudge });
2213
+ saveAuth(auth);
2214
+ await persistCloudIdentity();
2215
+ output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
2216
+ return;
2217
+ } catch (e) {
2218
+ if (!(e instanceof LoginSessionExpiredError)) {
2219
+ process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2220
+ `);
2221
+ process.exit(1);
2222
+ }
2223
+ }
2224
+ }
2225
+ await pendingLoginExit();
2226
+ process.exit(1);
2227
+ }
2228
+ clearPendingLogin();
1930
2229
  try {
1931
- const auth = await defaultBrowserLogin();
2230
+ const auth = noBrowserHuman ? await rendezvousLogin({
2231
+ onUrl: (u) => process.stderr.write(`Open this URL in your browser to sign in:
2232
+ ${u}
2233
+ `),
2234
+ onNudge: printLoginNudge,
2235
+ open: () => {
2236
+ }
2237
+ // INPLAN_NO_BROWSER: never launch one — the printed URL is the flow
2238
+ }) : await defaultRendezvousLogin();
1932
2239
  saveAuth(auth);
1933
2240
  await persistCloudIdentity();
1934
2241
  output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
@@ -1951,25 +2258,136 @@ function canInteractiveLogin(args) {
1951
2258
  if (process.env.CI || process.env.INPLAN_NO_BROWSER) return false;
1952
2259
  return Boolean(process.stdin.isTTY && process.stdout.isTTY);
1953
2260
  }
1954
- async function ensureLoggedIn(args, login = defaultBrowserLogin) {
2261
+ async function ensureLoggedIn(args, login = defaultRendezvousLogin, pendingExit = pendingLoginExit, pollPending = (p) => pollLoginSession(p, { onNudge: printLoginNudge })) {
1955
2262
  if (loadAuth()) return true;
1956
- if (!canInteractiveLogin(args)) return false;
2263
+ if (loginOptOut(args)) return false;
2264
+ const pending = await loadPendingLogin();
2265
+ if (pending) {
2266
+ try {
2267
+ process.stderr.write(`inplan: waiting for the pending browser sign-in to finish\u2026
2268
+ ${pending.url}
2269
+ `);
2270
+ saveAuth(await pollPending(pending));
2271
+ await persistCloudIdentity();
2272
+ return true;
2273
+ } catch (e) {
2274
+ if (!(e instanceof LoginSessionExpiredError)) {
2275
+ process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2276
+ `);
2277
+ return false;
2278
+ }
2279
+ }
2280
+ }
2281
+ if (canInteractiveLogin(args) && !isKnownAgentEnv()) {
2282
+ try {
2283
+ process.stderr.write("inplan: not signed in \u2014 opening your browser to sign in\u2026\n");
2284
+ saveAuth(await login());
2285
+ await persistCloudIdentity();
2286
+ return true;
2287
+ } catch (e) {
2288
+ process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2289
+ `);
2290
+ return false;
2291
+ }
2292
+ }
2293
+ await pendingExit();
2294
+ return false;
2295
+ }
2296
+ function loginOptOut(args) {
2297
+ return hasFlag(args, "no-login") || Boolean(process.env.CI);
2298
+ }
2299
+ function defaultRendezvousLogin() {
2300
+ return rendezvousLogin({
2301
+ onUrl: (u) => process.stderr.write(`Opening your browser to sign in:
2302
+ ${u}
2303
+ If it didn't open, paste that URL into your browser.
2304
+ `),
2305
+ onNudge: printLoginNudge
2306
+ });
2307
+ }
2308
+ function printLoginNudge() {
2309
+ process.stderr.write("inplan: still waiting \u2014 the browser may not have opened. Open the sign-in URL above manually to continue.\n");
2310
+ }
2311
+ function isKnownAgentEnv(env = process.env) {
2312
+ return Boolean(env.CLAUDECODE) || Object.keys(env).some((k) => k.startsWith("CLAUDE_CODE_"));
2313
+ }
2314
+ async function pendingLoginExit() {
2315
+ let url;
2316
+ let expiresInSec;
1957
2317
  try {
1958
- process.stderr.write("inplan: not signed in \u2014 opening your browser to sign in\u2026\n");
1959
- saveAuth(await login());
1960
- await persistCloudIdentity();
1961
- return true;
2318
+ const pending = await createLoginSession();
2319
+ url = pending.url;
2320
+ expiresInSec = Math.max(0, Math.floor((pending.expiresAt - Date.now()) / 1e3));
1962
2321
  } catch (e) {
1963
2322
  process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
1964
2323
  `);
1965
- return false;
2324
+ return;
1966
2325
  }
2326
+ const quoted = (a) => {
2327
+ if (/^[A-Za-z0-9_@%+=:,.\/-]+$/.test(a)) return a;
2328
+ return process.platform === "win32" ? `"${a.replaceAll('"', '""')}"` : shellQuote(a);
2329
+ };
2330
+ const argsSansCredentials = [];
2331
+ const skipValueOf = /* @__PURE__ */ new Set(["--refresh", "--anon", "--url"]);
2332
+ const argv = process.argv.slice(2);
2333
+ for (let i = 0; i < argv.length; i++) {
2334
+ const a = argv[i];
2335
+ if (skipValueOf.has(a)) {
2336
+ if (i + 1 < argv.length && !argv[i + 1].startsWith("--")) i++;
2337
+ continue;
2338
+ }
2339
+ if ([...skipValueOf].some((f) => a.startsWith(`${f}=`))) continue;
2340
+ argsSansCredentials.push(a);
2341
+ }
2342
+ const entry = process.argv[1] ?? "";
2343
+ const invokedAsInplan = entry.split(/[\\/]/).pop()?.replace(/\.(cmd|ps1)$/i, "") === "inplan";
2344
+ const argv0 = invokedAsInplan ? ["inplan"] : [quoted(process.execPath), quoted(entry)];
2345
+ const resume = [...argv0, ...argsSansCredentials.map(quoted)].join(" ");
2346
+ process.stderr.write(
2347
+ `inplan: sign-in required.
2348
+ ACTION (human): open this URL in a browser and sign in:
2349
+ ${url}
2350
+ NEXT STEP (coding agent): show that URL to the human, then immediately RE-RUN the
2351
+ command you just ran (\`${resume}\`) \u2014 it waits for the sign-in to finish, then continues.
2352
+ The link expires in ${Math.max(1, Math.round(expiresInSec / 60))} minutes.
2353
+ `
2354
+ );
2355
+ output({ status: "login_required", url, resume, expiresInSec });
2356
+ exitAfterFlush(EXIT_LOGIN_PENDING);
2357
+ await new Promise(() => {
2358
+ });
1967
2359
  }
1968
- function defaultBrowserLogin() {
1969
- return browserLogin({ onUrl: (u) => process.stderr.write(`Opening your browser to sign in:
1970
- ${u}
1971
- If it didn't open, paste that URL into your browser.
1972
- `) });
2360
+ function stalenessCache() {
2361
+ const path = join10(sidecarRoot(), ".update-check.json");
2362
+ return {
2363
+ readCache: () => existsSync10(path) ? readFileSync10(path, "utf8") : null,
2364
+ writeCache: (v) => {
2365
+ mkdirSync9(dirname10(path), { recursive: true });
2366
+ writeFileSync9(path, v);
2367
+ }
2368
+ };
2369
+ }
2370
+ var EXIT_UPGRADE_REQUIRED = 4;
2371
+ var EXIT_PLUGIN_UNAVAILABLE = 5;
2372
+ var EXIT_WAIT_FAILED = 6;
2373
+ var EXIT_LOGIN_PENDING = 7;
2374
+ function shellQuote(path) {
2375
+ return "'" + path.replaceAll("'", "'\\''") + "'";
2376
+ }
2377
+ function explainNoGate(reason, localFile) {
2378
+ if (reason === "unentitled") {
2379
+ process.stderr.write(
2380
+ "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.
2381
+ ` : "")
2382
+ );
2383
+ output({ status: "upgrade_required", reason, ...localFile ? { localFile } : {} });
2384
+ return;
2385
+ }
2386
+ process.stderr.write(
2387
+ "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)}\`.
2388
+ ` : "")
2389
+ );
2390
+ output({ status: "plugin_unavailable", reason, ...localFile ? { localFile } : {} });
1973
2391
  }
1974
2392
  async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile, model) {
1975
2393
  if (!await ensureLoggedIn(rest)) {
@@ -2007,121 +2425,105 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2007
2425
  output({ status: "messaged" });
2008
2426
  return;
2009
2427
  }
2428
+ await warnIfOutdated(UPDATE_PKG, VERSION, stalenessCache());
2010
2429
  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;
2430
+ const hubUrl = resolveHubUrl();
2431
+ const hubSession = JSON.stringify({ url: hubUrl, docName: docId, token: backend.token });
2432
+ const { gate, reason } = await loadPluginGateOutcome(hubSession, { token: backend.token });
2433
+ if (!gate) {
2434
+ explainNoGate(reason, localFile);
2435
+ exitAfterFlush(reason === "unentitled" ? EXIT_UPGRADE_REQUIRED : EXIT_PLUGIN_UNAVAILABLE);
2436
+ return;
2437
+ }
2018
2438
  const presence = announcePresence(docId, backend.token, model);
2019
2439
  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
2440
+ const workFile = join10(sidecarRoot(), "remote", `${docId}.plan.md`);
2441
+ const pendingPath = `${workFile}.pending`;
2442
+ const hashPath = `${workFile}.synced`;
2443
+ mkdirSync9(dirname10(workFile), { recursive: true });
2444
+ const readIf = (p) => existsSync10(p) ? readFileSync10(p, "utf8") : null;
2445
+ const recordSynced = (content) => writeFileSync9(hashPath, hashBody(content));
2446
+ let canonical = "";
2447
+ try {
2448
+ canonical = await gate.readCanonical();
2449
+ } catch (e) {
2450
+ process.stderr.write(`inplan: live-collab hub unreachable (${String(e)})
2036
2451
  `);
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
2452
+ explainNoGate("unavailable", localFile);
2453
+ exitAfterFlush(EXIT_PLUGIN_UNAVAILABLE);
2454
+ return;
2455
+ }
2456
+ const exists = existsSync10(workFile);
2457
+ if (shouldHydrateWorkFile({
2458
+ exists,
2459
+ pending: existsSync10(pendingPath),
2460
+ currentHash: exists ? hashBody(readFileSync10(workFile, "utf8")) : null,
2461
+ syncedHash: readIf(hashPath)
2462
+ })) {
2463
+ writeFileSync9(workFile, canonical);
2464
+ recordSynced(canonical);
2465
+ }
2466
+ const localStore = fsBackend(workFile).store;
2467
+ const gateStore = {
2468
+ loadDoc: () => localStore.loadDoc(),
2469
+ saveDoc: (c) => localStore.saveDoc(c),
2470
+ getCanonical: () => localStore.getCanonical(),
2471
+ setCanonical: (c) => localStore.setCanonical(c),
2472
+ backup: (c, m) => localStore.backup(c, m),
2473
+ getProposed: () => live.store.getProposed(),
2474
+ setProposed: (c) => live.store.setProposed(c),
2475
+ clearProposed: () => live.store.clearProposed()
2476
+ };
2477
+ const onSaveLocallyGate = localFile ? async () => {
2478
+ const body = await gate.readCanonical();
2479
+ writeFileSync9(localFile, body);
2480
+ writeStatus(docPaths(localFile).statusPath, { location: "local", originalPath: localFile, lastSyncedHash: hashBody(body) });
2481
+ const pid = spawnApp(localFile);
2482
+ output({ status: "moved_local", path: localFile, reopened: pid !== null });
2483
+ } : void 0;
2484
+ const tracked = trackGateDegradations(
2485
+ gate,
2486
+ localStore,
2487
+ (m) => process.stderr.write(`inplan: live-collab hub write failed (${m}); kept the edit locally to retry
2072
2488
  `)
2073
- );
2074
- process.stderr.write(`inplan: live-collab \u2014 plan at ${workFile}; read/edit it there, then re-run to sync
2489
+ );
2490
+ process.stderr.write(`inplan: live-collab \u2014 plan at ${workFile}; read/edit it there, then re-run to sync
2075
2491
  `);
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(
2492
+ const outcome = await waitCycle(
2112
2493
  {
2113
2494
  channel: live.channel,
2114
- store: live.store,
2495
+ // turns/comments still ride the cloud control log (self-refreshing)…
2496
+ store: gateStore,
2497
+ // …the agent reads/edits a local working copy; proposals go to the cloud…
2115
2498
  history: async () => (await live.channel.readSince(0)).entries,
2116
2499
  logExit: () => {
2117
2500
  },
2118
- // no local sidecar for a cloud doc
2119
- ...onSaveLocally ? { onSaveLocally } : {}
2501
+ ...onSaveLocallyGate ? { onSaveLocally: onSaveLocallyGate } : {}
2120
2502
  },
2121
2503
  explicitCursor,
2122
2504
  confirmed,
2123
- model
2505
+ model,
2506
+ tracked.gate
2507
+ // …and accepted edits apply through the hub, not the store.
2124
2508
  );
2509
+ const action = postTurnAction(outcome, { readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() });
2510
+ if (action === "stop") return;
2511
+ if (action === "keep-local") {
2512
+ if (pendingRequiresReplay({ readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() })) {
2513
+ writeFileSync9(pendingPath, "1");
2514
+ }
2515
+ process.stderr.write("inplan: hub was unavailable this turn \u2014 keeping local edits (will sync next turn)\n");
2516
+ } else {
2517
+ if (existsSync10(pendingPath)) rmSync2(pendingPath);
2518
+ recordSynced(readFileSync10(workFile, "utf8"));
2519
+ try {
2520
+ const fresh = await gate.readCanonical();
2521
+ writeFileSync9(workFile, fresh);
2522
+ recordSynced(fresh);
2523
+ } catch {
2524
+ }
2525
+ }
2526
+ return;
2125
2527
  } finally {
2126
2528
  presence.destroy();
2127
2529
  }
@@ -2135,7 +2537,7 @@ function doPromote(file, args) {
2135
2537
  process.stderr.write("usage: inplan promote <file> --cloud-doc <docId> [--locator org/repo/path]\n");
2136
2538
  process.exit(64);
2137
2539
  }
2138
- const body = existsSync9(file) ? readFileSync9(file, "utf8") : "";
2540
+ const body = existsSync10(file) ? readFileSync10(file, "utf8") : "";
2139
2541
  const status = { location: "cloud", cloudDocId, originalPath: file, lastSyncedHash: hashBody(body) };
2140
2542
  const locator = getFlag(args, "locator");
2141
2543
  if (locator) {
@@ -2157,11 +2559,32 @@ async function doDemote(file, args) {
2157
2559
  process.stderr.write("inplan: not logged in (or session expired) \u2014 run `inplan login`\n");
2158
2560
  process.exit(1);
2159
2561
  }
2160
- const body = await backend.store.loadDoc();
2562
+ const hubSession = JSON.stringify({ url: resolveHubUrl(), docName: st.cloudDocId, token: backend.token });
2563
+ const { gate } = await loadPluginGateOutcome(hubSession, { token: backend.token });
2564
+ let hubBody = null;
2565
+ try {
2566
+ if (gate) hubBody = await gate.readCanonical();
2567
+ } catch {
2568
+ hubBody = null;
2569
+ }
2161
2570
  const dest = st.originalPath ?? file;
2162
- writeFileSync8(dest, body);
2571
+ const choice = demoteSource({ hubReadable: hubBody !== null, fromStore: hasFlag(args, "from-store") });
2572
+ if (choice.use === "abort") {
2573
+ process.stderr.write(
2574
+ `inplan demote: couldn't read the live document from the collab hub.
2575
+ The server copy may be missing edits made through the hub, and demoting overwrites ${shellQuote(dest)}
2576
+ and switches the document to local \u2014 together, that can't be undone.
2577
+ Retry when the hub is reachable, or re-run with --from-store to accept the server copy as-is.
2578
+ `
2579
+ );
2580
+ output({ status: "demote_blocked", reason: choice.reason, path: dest });
2581
+ exitAfterFlush(EXIT_PLUGIN_UNAVAILABLE);
2582
+ return;
2583
+ }
2584
+ const body = choice.use === "hub" ? hubBody : await backend.store.loadDoc();
2585
+ writeFileSync9(dest, body);
2163
2586
  writeStatus(p.statusPath, { location: "local", originalPath: dest, lastSyncedHash: hashBody(body) });
2164
- output({ status: "demoted", location: "local", path: dest });
2587
+ output({ status: "demoted", location: "local", path: dest, source: choice.use });
2165
2588
  }
2166
2589
  function firstHeading(body) {
2167
2590
  return body.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() || null;
@@ -2194,16 +2617,16 @@ async function doToken() {
2194
2617
  function bundledSkillPath() {
2195
2618
  try {
2196
2619
  const override = process.env.INPLAN_SKILL_SRC;
2197
- if (override) return existsSync9(override) ? override : null;
2198
- const p = join9(dirname9(fileURLToPath2(import.meta.url)), "..", "skill", "SKILL.md");
2199
- return existsSync9(p) ? p : null;
2620
+ if (override) return existsSync10(override) ? override : null;
2621
+ const p = join10(dirname10(fileURLToPath2(import.meta.url)), "..", "skill", "SKILL.md");
2622
+ return existsSync10(p) ? p : null;
2200
2623
  } catch {
2201
2624
  return null;
2202
2625
  }
2203
2626
  }
2204
2627
  function activeDocForCwd(cwd) {
2205
2628
  const root = sidecarRoot();
2206
- if (!existsSync9(root)) return null;
2629
+ if (!existsSync10(root)) return null;
2207
2630
  const real = (p) => {
2208
2631
  try {
2209
2632
  return realpathSync(p);
@@ -2215,13 +2638,13 @@ function activeDocForCwd(cwd) {
2215
2638
  let best = null;
2216
2639
  for (const entry of readdirSync2(root)) {
2217
2640
  try {
2218
- const dir = join9(root, entry);
2219
- const orig = readStatus(join9(dir, "status.json")).originalPath;
2641
+ const dir = join10(root, entry);
2642
+ const orig = readStatus(join10(dir, "status.json")).originalPath;
2220
2643
  if (!orig) continue;
2221
2644
  const rel = relative4(base2, real(orig));
2222
2645
  if (rel === "" || rel.startsWith("..") || isAbsolute2(rel)) continue;
2223
- const logPath = join9(dir, "log.jsonl");
2224
- const mtime = existsSync9(logPath) ? statSync3(logPath).mtimeMs : 0;
2646
+ const logPath = join10(dir, "log.jsonl");
2647
+ const mtime = existsSync10(logPath) ? statSync4(logPath).mtimeMs : 0;
2225
2648
  if (!best || mtime > best.mtime) best = { file: resolve3(orig), mtime };
2226
2649
  } catch {
2227
2650
  }
@@ -2230,11 +2653,11 @@ function activeDocForCwd(cwd) {
2230
2653
  }
2231
2654
  function relayCursorPath(sessionKey) {
2232
2655
  const id = createHash4("sha1").update(sessionKey).digest("hex").slice(0, 16);
2233
- return join9(sidecarRoot(), ".relay-cursors", `${id}.json`);
2656
+ return join10(sidecarRoot(), ".relay-cursors", `${id}.json`);
2234
2657
  }
2235
2658
  function readRelayCursor(sessionKey) {
2236
2659
  try {
2237
- const v = JSON.parse(readFileSync9(relayCursorPath(sessionKey), "utf8"));
2660
+ const v = JSON.parse(readFileSync10(relayCursorPath(sessionKey), "utf8"));
2238
2661
  return typeof v.sent === "number" && v.sent >= 0 ? v.sent : 0;
2239
2662
  } catch {
2240
2663
  return 0;
@@ -2243,8 +2666,8 @@ function readRelayCursor(sessionKey) {
2243
2666
  function writeRelayCursor(sessionKey, sent) {
2244
2667
  try {
2245
2668
  const p = relayCursorPath(sessionKey);
2246
- mkdirSync8(dirname9(p), { recursive: true });
2247
- writeFileSync8(p, JSON.stringify({ sent }) + "\n");
2669
+ mkdirSync9(dirname10(p), { recursive: true });
2670
+ writeFileSync9(p, JSON.stringify({ sent }) + "\n");
2248
2671
  } catch {
2249
2672
  }
2250
2673
  }
@@ -2252,7 +2675,7 @@ function transcriptTextBlocks(path) {
2252
2675
  const out = [];
2253
2676
  let raw;
2254
2677
  try {
2255
- raw = readFileSync9(path, "utf8");
2678
+ raw = readFileSync10(path, "utf8");
2256
2679
  } catch {
2257
2680
  return out;
2258
2681
  }
@@ -2297,7 +2720,7 @@ function notesFromHook(kind, stdin, argv) {
2297
2720
  const p = parse2(stdin);
2298
2721
  const transcript = str(p.transcript_path);
2299
2722
  const sessionKey = str(p.session_id) || transcript;
2300
- const blocks = transcript && existsSync9(transcript) && sessionKey ? transcriptTextBlocks(transcript) : [];
2723
+ const blocks = transcript && existsSync10(transcript) && sessionKey ? transcriptTextBlocks(transcript) : [];
2301
2724
  if (blocks.length > 0) {
2302
2725
  const sent = readRelayCursor(sessionKey);
2303
2726
  for (let i = Math.max(0, sent); i < blocks.length; i++) notes.push(blocks[i]);
@@ -2321,7 +2744,7 @@ async function relayText(file, text) {
2321
2744
  await backend.channel.append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
2322
2745
  } else if (route.kind === "local") {
2323
2746
  const p = docPaths(file);
2324
- mkdirSync8(p.controlDir, { recursive: true });
2747
+ mkdirSync9(p.controlDir, { recursive: true });
2325
2748
  await new FsControlChannel(p).append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
2326
2749
  }
2327
2750
  } catch {
@@ -2339,7 +2762,7 @@ async function doRelay(args) {
2339
2762
  let stdin = "";
2340
2763
  if (hook !== "codex-notify") {
2341
2764
  try {
2342
- stdin = readFileSync9(0, "utf8");
2765
+ stdin = readFileSync10(0, "utf8");
2343
2766
  } catch {
2344
2767
  }
2345
2768
  }
@@ -2357,22 +2780,22 @@ async function doRelay(args) {
2357
2780
  output({ status: "relayed", count: clean.length });
2358
2781
  }
2359
2782
  function skillTargets() {
2360
- const home = homedir6();
2783
+ const home = homedir7();
2361
2784
  return [
2362
- { name: "Claude Code", root: join9(home, ".claude"), target: join9(home, ".claude", "skills", "inplan", "SKILL.md") },
2363
- { name: "Pi", root: join9(home, ".pi", "agent"), target: join9(home, ".pi", "agent", "skills", "inplan", "SKILL.md") },
2364
- { name: "Codex", root: join9(home, ".codex"), target: join9(home, ".codex", "skills", "inplan", "SKILL.md") }
2785
+ { name: "Claude Code", root: join10(home, ".claude"), target: join10(home, ".claude", "skills", "inplan", "SKILL.md") },
2786
+ { name: "Pi", root: join10(home, ".pi", "agent"), target: join10(home, ".pi", "agent", "skills", "inplan", "SKILL.md") },
2787
+ { name: "Codex", root: join10(home, ".codex"), target: join10(home, ".codex", "skills", "inplan", "SKILL.md") }
2365
2788
  ];
2366
2789
  }
2367
2790
  var SKILL_ALLOW = ["Bash(inplan *)", "Edit(**/*.plan.md)", "Read(~/.inplan/**)", "Edit(~/.inplan/**)"];
2368
2791
  var SKILL_ALLOW_OBSOLETE = ["Write(**/*.plan.md)", "Write(~/.inplan/**)"];
2369
2792
  var SKILL_DIRS = ["~/.inplan/"];
2370
2793
  function grantClaudePermissions(claudeRoot) {
2371
- const settingsPath = join9(claudeRoot, "settings.json");
2794
+ const settingsPath = join10(claudeRoot, "settings.json");
2372
2795
  let settings = {};
2373
2796
  try {
2374
- if (existsSync9(settingsPath)) {
2375
- const parsed = JSON.parse(readFileSync9(settingsPath, "utf8"));
2797
+ if (existsSync10(settingsPath)) {
2798
+ const parsed = JSON.parse(readFileSync10(settingsPath, "utf8"));
2376
2799
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
2377
2800
  settings = parsed;
2378
2801
  }
@@ -2405,7 +2828,7 @@ function grantClaudePermissions(claudeRoot) {
2405
2828
  settings.permissions = perms;
2406
2829
  try {
2407
2830
  const tmp = settingsPath + ".tmp";
2408
- writeFileSync8(tmp, JSON.stringify(settings, null, 2) + "\n");
2831
+ writeFileSync9(tmp, JSON.stringify(settings, null, 2) + "\n");
2409
2832
  renameSync2(tmp, settingsPath);
2410
2833
  } catch {
2411
2834
  return false;
@@ -2451,8 +2874,8 @@ function mergeRelayHooks(settings, entries) {
2451
2874
  }
2452
2875
  function readJsonObject(path) {
2453
2876
  try {
2454
- if (!existsSync9(path)) return {};
2455
- const parsed = JSON.parse(readFileSync9(path, "utf8"));
2877
+ if (!existsSync10(path)) return {};
2878
+ const parsed = JSON.parse(readFileSync10(path, "utf8"));
2456
2879
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
2457
2880
  return parsed;
2458
2881
  } catch {
@@ -2461,9 +2884,9 @@ function readJsonObject(path) {
2461
2884
  }
2462
2885
  function writeJsonAtomic(path, value) {
2463
2886
  try {
2464
- mkdirSync8(dirname9(path), { recursive: true });
2887
+ mkdirSync9(dirname10(path), { recursive: true });
2465
2888
  const tmp = path + ".tmp";
2466
- writeFileSync8(tmp, JSON.stringify(value, null, 2) + "\n");
2889
+ writeFileSync9(tmp, JSON.stringify(value, null, 2) + "\n");
2467
2890
  renameSync2(tmp, path);
2468
2891
  return true;
2469
2892
  } catch {
@@ -2471,13 +2894,13 @@ function writeJsonAtomic(path, value) {
2471
2894
  }
2472
2895
  }
2473
2896
  function installClaudeHooks(claudeRoot) {
2474
- const path = join9(claudeRoot, "settings.json");
2897
+ const path = join10(claudeRoot, "settings.json");
2475
2898
  const settings = readJsonObject(path);
2476
2899
  if (!settings || !mergeRelayHooks(settings, CLAUDE_RELAY_HOOKS)) return false;
2477
2900
  return writeJsonAtomic(path, settings);
2478
2901
  }
2479
2902
  function installCodexHooks(codexRoot) {
2480
- const path = join9(codexRoot, "hooks.json");
2903
+ const path = join10(codexRoot, "hooks.json");
2481
2904
  const cfg = readJsonObject(path);
2482
2905
  if (!cfg || !mergeRelayHooks(cfg, CODEX_RELAY_HOOKS)) return false;
2483
2906
  return writeJsonAtomic(path, cfg);
@@ -2527,16 +2950,16 @@ export default function (pi) {
2527
2950
  }
2528
2951
  `;
2529
2952
  function installPiRelayExtension(piAgentRoot) {
2530
- const path = join9(piAgentRoot, "extensions", "inplan-relay.ts");
2953
+ const path = join10(piAgentRoot, "extensions", "inplan-relay.ts");
2531
2954
  try {
2532
- if (existsSync9(path)) {
2533
- const cur = readFileSync9(path, "utf8");
2955
+ if (existsSync10(path)) {
2956
+ const cur = readFileSync10(path, "utf8");
2534
2957
  if (cur === PI_RELAY_EXTENSION) return false;
2535
2958
  if (!cur.startsWith(PI_RELAY_MARKER)) return false;
2536
2959
  }
2537
- mkdirSync8(dirname9(path), { recursive: true });
2960
+ mkdirSync9(dirname10(path), { recursive: true });
2538
2961
  const tmp = path + ".tmp";
2539
- writeFileSync8(tmp, PI_RELAY_EXTENSION);
2962
+ writeFileSync9(tmp, PI_RELAY_EXTENSION);
2540
2963
  renameSync2(tmp, path);
2541
2964
  return true;
2542
2965
  } catch {
@@ -2557,28 +2980,28 @@ function doInstallSkill(args) {
2557
2980
  const installed = [];
2558
2981
  for (const a of skillTargets()) {
2559
2982
  try {
2560
- if (!existsSync9(a.root)) continue;
2561
- if (!existsSync9(a.target)) {
2562
- mkdirSync8(dirname9(a.target), { recursive: true });
2983
+ if (!existsSync10(a.root)) continue;
2984
+ if (!existsSync10(a.target)) {
2985
+ mkdirSync9(dirname10(a.target), { recursive: true });
2563
2986
  copyFileSync(src, a.target);
2564
2987
  installed.push(a.name);
2565
2988
  process.stderr.write(`inplan: installed the inplan skill into ${a.name} (${a.target}). Set INPLAN_NO_SKILL_INSTALL=1 to skip.
2566
2989
  `);
2567
2990
  }
2568
2991
  if (a.name === "Claude Code" && grantClaudePermissions(a.root)) {
2569
- process.stderr.write(`inplan: granted scoped auto-approval (plan files + ~/.inplan + inplan CLI) in ${join9(a.root, "settings.json")}.
2992
+ process.stderr.write(`inplan: granted scoped auto-approval (plan files + ~/.inplan + inplan CLI) in ${join10(a.root, "settings.json")}.
2570
2993
  `);
2571
2994
  }
2572
2995
  if (a.name === "Claude Code" && installClaudeHooks(a.root)) {
2573
- process.stderr.write(`inplan: configured the agent-console relay hooks in ${join9(a.root, "settings.json")}.
2996
+ process.stderr.write(`inplan: configured the agent-console relay hooks in ${join10(a.root, "settings.json")}.
2574
2997
  `);
2575
2998
  }
2576
2999
  if (a.name === "Codex" && installCodexHooks(a.root)) {
2577
- process.stderr.write(`inplan: configured the agent-console relay hooks in ${join9(a.root, "hooks.json")}.
3000
+ process.stderr.write(`inplan: configured the agent-console relay hooks in ${join10(a.root, "hooks.json")}.
2578
3001
  `);
2579
3002
  }
2580
3003
  if (a.name === "Pi" && installPiRelayExtension(a.root)) {
2581
- process.stderr.write(`inplan: installed the agent-console relay extension in ${join9(a.root, "extensions", "inplan-relay.ts")}.
3004
+ process.stderr.write(`inplan: installed the agent-console relay extension in ${join10(a.root, "extensions", "inplan-relay.ts")}.
2582
3005
  `);
2583
3006
  }
2584
3007
  } catch {
@@ -2612,7 +3035,7 @@ async function doUpload(file, args) {
2612
3035
  process.exit(1);
2613
3036
  }
2614
3037
  const org = orgOf(pick);
2615
- const body = existsSync9(file) ? readFileSync9(file, "utf8") : "";
3038
+ const body = existsSync10(file) ? readFileSync10(file, "utf8") : "";
2616
3039
  const prov = gitProvenance(file);
2617
3040
  const repo = getFlag(args, "repo") ?? prov.repo;
2618
3041
  const path = getFlag(args, "path") ?? prov.path;
@@ -2673,8 +3096,8 @@ function routeFor(file, cmd, args) {
2673
3096
  const status = readStatus(p.statusPath);
2674
3097
  if (status.location !== "cloud" || !status.cloudDocId) return { kind: "local" };
2675
3098
  const docId = status.cloudDocId;
2676
- if (cmd === "signal" || cmd === "message" || !existsSync9(file)) return { kind: "cloud", docId };
2677
- const local = readFileSync9(file, "utf8");
3099
+ if (cmd === "signal" || cmd === "message" || !existsSync10(file)) return { kind: "cloud", docId };
3100
+ const local = readFileSync10(file, "utf8");
2678
3101
  const diverged = status.lastSyncedHash !== void 0 && hashBody(local) !== status.lastSyncedHash;
2679
3102
  if (!diverged || hasFlag(args, "use-cloud")) return { kind: "cloud", docId };
2680
3103
  if (hasFlag(args, "continue-locally")) {
@@ -2735,7 +3158,7 @@ async function main() {
2735
3158
  );
2736
3159
  if (!cmd || !["open", "wait", "signal", "message", "comment", "relay", "status", "promote", "demote", "upload"].includes(cmd)) {
2737
3160
  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'
3161
+ '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
3162
  );
2740
3163
  process.exit(64);
2741
3164
  }
@@ -2792,7 +3215,7 @@ async function main() {
2792
3215
  }
2793
3216
  if (cmd === "signal") {
2794
3217
  const p = docPaths(file);
2795
- mkdirSync8(p.controlDir, { recursive: true });
3218
+ mkdirSync9(p.controlDir, { recursive: true });
2796
3219
  const channel = new FsControlChannel(p);
2797
3220
  if (hasFlag(args, "done")) {
2798
3221
  await channel.append({ actor: "agent", type: LogEventType.AgentDoneSuggested });
@@ -2810,13 +3233,13 @@ async function main() {
2810
3233
  process.exit(1);
2811
3234
  }
2812
3235
  const p = docPaths(file);
2813
- mkdirSync8(p.controlDir, { recursive: true });
3236
+ mkdirSync9(p.controlDir, { recursive: true });
2814
3237
  const channel = new FsControlChannel(p);
2815
3238
  await channel.append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
2816
3239
  output({ status: "messaged" });
2817
3240
  return;
2818
3241
  }
2819
- if (cmd !== "open" && !existsSync9(file)) {
3242
+ if (cmd !== "open" && !existsSync10(file)) {
2820
3243
  process.stderr.write(`inplan ${cmd}: file not found: ${file}
2821
3244
  `);
2822
3245
  process.exit(1);
@@ -2842,7 +3265,7 @@ async function main() {
2842
3265
  }
2843
3266
  }
2844
3267
  try {
2845
- const currentText = readFileSync9(file, "utf8");
3268
+ const currentText = readFileSync10(file, "utf8");
2846
3269
  const { text: nextText, comment } = addComment(currentText, {
2847
3270
  text,
2848
3271
  author: agentAuthorFor(model),
@@ -2852,7 +3275,7 @@ async function main() {
2852
3275
  ...question ? { question } : {},
2853
3276
  mayResolve: hasFlag(args, "may-resolve")
2854
3277
  });
2855
- writeFileSync8(file, nextText);
3278
+ writeFileSync9(file, nextText);
2856
3279
  output({ status: "commented", id: comment.id, date: comment.date, author: comment.author });
2857
3280
  } catch (err) {
2858
3281
  if (err instanceof AddCommentError) {
@@ -2867,7 +3290,7 @@ async function main() {
2867
3290
  if (cmd === "open") {
2868
3291
  ensureDocFile(file);
2869
3292
  const p = docPaths(file);
2870
- mkdirSync8(p.controlDir, { recursive: true });
3293
+ mkdirSync9(p.controlDir, { recursive: true });
2871
3294
  const st = readStatus(p.statusPath);
2872
3295
  if (st.location !== "cloud") writeStatus(p.statusPath, { ...st, location: "local", originalPath: file });
2873
3296
  const existing = runningEditorPid(p.logPath);
@@ -2899,17 +3322,36 @@ function isProgramEntry() {
2899
3322
  }
2900
3323
  }
2901
3324
  if (isProgramEntry()) {
3325
+ let exitingForUnhandledRejection = false;
3326
+ process.on("unhandledRejection", (reason) => {
3327
+ if (exitingForUnhandledRejection) return;
3328
+ exitingForUnhandledRejection = true;
3329
+ const message = reason instanceof Error ? reason.message : String(reason);
3330
+ process.stderr.write(`inplan: unexpected error \u2014 ${message}
3331
+ `);
3332
+ output({ status: "internal_error", message });
3333
+ exitAfterFlush(1);
3334
+ });
2902
3335
  main().catch((err) => {
2903
3336
  process.stderr.write(`inplan: ${err.message}
2904
3337
  `);
2905
- process.exit(1);
3338
+ output({ status: "internal_error", message: err.message });
3339
+ exitAfterFlush(1);
2906
3340
  });
2907
3341
  }
2908
3342
  export {
3343
+ EXIT_LOGIN_PENDING,
3344
+ EXIT_PLUGIN_UNAVAILABLE,
3345
+ EXIT_UPGRADE_REQUIRED,
3346
+ EXIT_WAIT_FAILED,
2909
3347
  activeDocForCwd,
2910
3348
  canInteractiveLogin,
2911
3349
  doUpload,
2912
3350
  ensureLoggedIn,
3351
+ exitAfterFlush,
3352
+ explainNoGate,
3353
+ isKnownAgentEnv,
2913
3354
  notesFromHook,
3355
+ shellQuote,
2914
3356
  transcriptTextBlocks
2915
3357
  };