inplan 0.1.27 → 0.1.29

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,12 +4,12 @@
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
- // ../core/dist/chunk-2A42CIA7.js
12
+ // ../core/dist/chunk-BS76FGIJ.js
13
13
  function isReply(c) {
14
14
  return c.parentId !== void 0;
15
15
  }
@@ -372,7 +372,9 @@ var FsControlChannel = class {
372
372
  if (!existsSync2(this.paths.waitLockPath)) return Promise.resolve(false);
373
373
  return Promise.resolve(readFileSync2(this.paths.waitLockPath, "utf8").trim() !== token);
374
374
  }
375
- presence() {
375
+ // `sinceMs` is ignored: liveness here is "is the editor PROCESS alive", which flips to false the
376
+ // instant the window closes — there's no lingering-heartbeat TTL window to disambiguate.
377
+ presence(_sinceMs) {
376
378
  const log = readLog(this.paths.logPath);
377
379
  for (let i = log.length - 1; i >= 0; i--) {
378
380
  if (log[i].type === LogEventType.EditorPid) {
@@ -512,7 +514,7 @@ function writeStatus(statusPath, status) {
512
514
  writeFileSync4(statusPath, `${JSON.stringify(status, null, 2)}
513
515
  `);
514
516
  }
515
- var PLUGIN_PUBLIC_KEY = process.env.INPLAN_PLUGIN_PUBLIC_KEY ?? "";
517
+ var PLUGIN_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAVP11te5E7xzNJ4reKg0+mAnrr91gcyD1bMr43Homq98=\n-----END PUBLIC KEY-----\n";
516
518
  function verifyLease(token, publicKeyPem = PLUGIN_PUBLIC_KEY, now = Date.now()) {
517
519
  try {
518
520
  if (!publicKeyPem || typeof token !== "string") return null;
@@ -745,12 +747,13 @@ var SupabaseControlChannel = class {
745
747
  const current = data?.token;
746
748
  return current != null && current !== token;
747
749
  }
748
- async presence() {
750
+ async presence(sinceMs) {
749
751
  const { data, error } = await this.db.from("editor_presence").select("last_seen").eq("doc_id", this.docId).maybeSingle();
750
752
  if (error) throw new Error(`presence failed: ${error.message}`);
751
753
  const lastSeen = data?.last_seen;
752
754
  if (!lastSeen) return false;
753
- return Date.now() - new Date(lastSeen).getTime() < PRESENCE_TTL_MS;
755
+ const lastSeenMs = new Date(lastSeen).getTime();
756
+ return sinceMs !== void 0 ? lastSeenMs > sinceMs : Date.now() - lastSeenMs < PRESENCE_TTL_MS;
754
757
  }
755
758
  };
756
759
  function rowToEntry(r) {
@@ -1038,7 +1041,7 @@ function liveRemoteBackend(docId, consumerId = "cli-agent") {
1038
1041
  setCursor: async (s) => (await need()).channel.setCursor(s),
1039
1042
  claimLock: async (t) => (await need()).channel.claimLock(t),
1040
1043
  isSuperseded: async (t) => (await need()).channel.isSuperseded(t),
1041
- presence: async () => (await need()).channel.presence()
1044
+ presence: async (sinceMs) => (await need()).channel.presence(sinceMs)
1042
1045
  };
1043
1046
  const store = {
1044
1047
  loadDoc: async () => (await need()).store.loadDoc(),
@@ -1054,115 +1057,289 @@ function liveRemoteBackend(docId, consumerId = "cli-agent") {
1054
1057
  }
1055
1058
 
1056
1059
  // src/cliLogin.ts
1057
- import { createServer } from "http";
1058
1060
  import { spawn } from "child_process";
1059
- import { randomBytes } from "crypto";
1061
+ import { webcrypto } from "crypto";
1062
+ 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";
1063
+ import { homedir as homedir5 } from "os";
1064
+ import { dirname as dirname6, join as join7 } from "path";
1065
+
1066
+ // src/pluginGate.ts
1067
+ import { homedir as homedir4 } from "os";
1068
+ import { join as join6 } from "path";
1069
+ import { pathToFileURL } from "url";
1070
+ var DEFAULT_HUB_URL = "wss://inplan-collab.fly.dev";
1071
+ var resolveHubUrl = () => process.env.INPLAN_PLUGIN_URL || process.env.INPLAN_COLLAB_URL || DEFAULT_HUB_URL;
1072
+ var hubHttpBase = () => resolveHubUrl().replace(/^ws/, "http").replace(/\/+$/, "");
1073
+ var PLUGIN_HTTP = hubHttpBase();
1074
+ var defaultCacheDir = () => join6(process.env.INPLAN_HOME || join6(homedir4(), ".inplan"), "plugin-cache");
1075
+ var defaultDeps = {
1076
+ resolve: resolvePluginOutcome,
1077
+ importCli: (p) => import(pathToFileURL(p).href)
1078
+ };
1079
+ async function loadPluginGateOutcome(session, options, deps = defaultDeps) {
1080
+ try {
1081
+ const { plugin, reason } = await deps.resolve({
1082
+ apiBase: options.apiBase ?? PLUGIN_HTTP,
1083
+ token: options.token,
1084
+ cacheDir: options.cacheDir ?? defaultCacheDir(),
1085
+ // Forward whenever DEFINED, not whenever truthy: an explicit `""` means "nothing can be
1086
+ // verified" and must reach the resolver, which then refuses without a network call. Dropping
1087
+ // it would silently substitute the baked-in key and verify against something the caller
1088
+ // deliberately disabled.
1089
+ ...options.publicKey !== void 0 ? { publicKey: options.publicKey } : {}
1090
+ });
1091
+ if (!plugin) return { gate: null, reason };
1092
+ const cliName = plugin.entries.cli;
1093
+ const cliPath = cliName ? plugin.files[cliName] : void 0;
1094
+ if (!cliPath) return { gate: null, reason: "unavailable" };
1095
+ const cli = await deps.importCli(cliPath);
1096
+ return { gate: cli.gate(session), reason: null };
1097
+ } catch {
1098
+ return { gate: null, reason: "unavailable" };
1099
+ }
1100
+ }
1101
+ async function loadPluginGate(session, options, deps = defaultDeps) {
1102
+ try {
1103
+ return (await loadPluginGateOutcome(session, options, deps)).gate;
1104
+ } catch {
1105
+ return null;
1106
+ }
1107
+ }
1108
+
1109
+ // src/cliLogin.ts
1110
+ var subtle = webcrypto.subtle;
1060
1111
  var DEFAULT_WEB_ORIGIN = process.env.INPLAN_WEB_URL || "https://inplan.ai";
1112
+ var HKDF_INFO = "inplan cli-login v1";
1061
1113
  var DEFAULT_TIMEOUT_MS = 3 * 6e4;
1062
- var MAX_BODY_BYTES = 64 * 1024;
1063
- function openInBrowser(url) {
1064
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1065
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
1114
+ var POLL_MS = 2e3;
1115
+ var NUDGE_MS = 3e4;
1116
+ var REQUEST_TIMEOUT_MS = 15e3;
1117
+ function loginApiBase() {
1118
+ return hubHttpBase();
1119
+ }
1120
+ function pendingLoginPath() {
1121
+ const base2 = process.env.INPLAN_HOME || join7(homedir5(), ".inplan");
1122
+ return join7(base2, "login-pending.json");
1123
+ }
1124
+ function clearPendingLogin() {
1066
1125
  try {
1067
- const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
1068
- child.on("error", () => {
1069
- });
1070
- child.unref();
1126
+ unlinkSync2(pendingLoginPath());
1071
1127
  } catch {
1072
1128
  }
1073
1129
  }
1074
- function isHandoff(v) {
1075
- if (typeof v !== "object" || v === null) return false;
1076
- const o = v;
1077
- 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");
1130
+ var LOCK_WAIT_MS2 = 2e3;
1131
+ var LOCK_RETRY_MS = 25;
1132
+ var LOCK_STALE_MS2 = 5e3;
1133
+ async function withSidecarLock(fn) {
1134
+ const lock = pendingLoginPath() + ".lock";
1135
+ const deadline = Date.now() + LOCK_WAIT_MS2;
1136
+ for (; ; ) {
1137
+ try {
1138
+ mkdirSync6(lock, { recursive: false });
1139
+ break;
1140
+ } catch (e) {
1141
+ if (e.code !== "EEXIST") throw e;
1142
+ try {
1143
+ if (Date.now() - statSync3(lock).mtimeMs > LOCK_STALE_MS2) rmdirSync(lock);
1144
+ } catch {
1145
+ }
1146
+ if (Date.now() > deadline) throw new Error("could not acquire the login lock \u2014 another inplan process is holding it");
1147
+ await new Promise((r) => setTimeout(r, LOCK_RETRY_MS));
1148
+ }
1149
+ }
1150
+ try {
1151
+ return await fn();
1152
+ } finally {
1153
+ try {
1154
+ rmdirSync(lock);
1155
+ } catch {
1156
+ }
1157
+ }
1078
1158
  }
1079
- function browserLogin(opts = {}) {
1159
+ async function clearPendingLoginFor(sessionId) {
1160
+ await withSidecarLock(() => {
1161
+ const path = pendingLoginPath();
1162
+ try {
1163
+ const p = JSON.parse(readFileSync7(path, "utf8"));
1164
+ if (p.sessionId !== sessionId) return;
1165
+ } catch {
1166
+ }
1167
+ clearPendingLogin();
1168
+ });
1169
+ }
1170
+ function loadPendingLoginLocked(now) {
1171
+ const path = pendingLoginPath();
1172
+ if (!existsSync8(path)) return null;
1173
+ try {
1174
+ const p = JSON.parse(readFileSync7(path, "utf8"));
1175
+ 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) {
1176
+ clearPendingLogin();
1177
+ return null;
1178
+ }
1179
+ return p;
1180
+ } catch {
1181
+ clearPendingLogin();
1182
+ return null;
1183
+ }
1184
+ }
1185
+ function loadPendingLogin(now = Date.now()) {
1186
+ return withSidecarLock(() => loadPendingLoginLocked(now));
1187
+ }
1188
+ async function createLoginSession(opts = {}) {
1189
+ const fetchImpl = opts.fetchImpl ?? fetch;
1190
+ const now = opts.now ?? Date.now;
1191
+ const existing = await loadPendingLogin(now());
1192
+ if (existing) return existing;
1193
+ const apiBase = opts.apiBase ?? loginApiBase();
1080
1194
  const webOrigin = (opts.webOrigin ?? DEFAULT_WEB_ORIGIN).replace(/\/$/, "");
1081
- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1082
- const open = opts.open ?? openInBrowser;
1083
- const state = randomBytes(16).toString("hex");
1084
- return new Promise((resolve4, reject) => {
1085
- let settled = false;
1086
- const finish = (fn) => {
1087
- if (settled) return;
1088
- settled = true;
1089
- clearTimeout(timer);
1090
- server.close();
1091
- fn();
1092
- };
1093
- const cors = (req, res) => {
1094
- res.setHeader("Access-Control-Allow-Origin", req.headers.origin || webOrigin);
1095
- res.setHeader("Vary", "Origin");
1096
- res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
1097
- res.setHeader("Access-Control-Allow-Headers", "content-type");
1098
- };
1099
- const server = createServer((req, res) => {
1100
- const url = req.url ?? "";
1101
- if (req.method === "OPTIONS" && url.startsWith("/cb")) {
1102
- cors(req, res);
1103
- res.writeHead(204).end();
1104
- return;
1105
- }
1106
- if (req.method !== "POST" || !url.startsWith("/cb")) {
1107
- res.writeHead(404).end();
1108
- return;
1109
- }
1110
- cors(req, res);
1111
- let body = "";
1112
- let tooBig = false;
1113
- req.on("data", (chunk) => {
1114
- body += chunk.toString("utf8");
1115
- if (body.length > MAX_BODY_BYTES) {
1116
- tooBig = true;
1117
- req.destroy();
1118
- }
1195
+ const keys = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, true, ["deriveBits"]);
1196
+ const pub = Buffer.from(await subtle.exportKey("spki", keys.publicKey)).toString("base64");
1197
+ const priv = Buffer.from(await subtle.exportKey("pkcs8", keys.privateKey)).toString("base64");
1198
+ const res = await fetchImpl(`${apiBase}/api/v1/cli-login`, { method: "POST", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
1199
+ if (!res.ok) throw new Error(`could not start a sign-in session (HTTP ${res.status})`);
1200
+ const { sessionId, pollToken, expiresInSec } = await res.json();
1201
+ if (typeof sessionId !== "string" || !sessionId || typeof pollToken !== "string" || !pollToken) {
1202
+ throw new Error("could not start a sign-in session (bad response)");
1203
+ }
1204
+ const pending = {
1205
+ sessionId,
1206
+ privateKeyPkcs8: priv,
1207
+ pollToken,
1208
+ // `pub` rides the URL FRAGMENT so it never reaches server access logs (a log reader holding
1209
+ // session + pub could complete the session for their own account); the page reads it from
1210
+ // location.hash. Public key or not, keep the whole capability out of logs.
1211
+ url: `${webOrigin}/cli-auth?session=${encodeURIComponent(sessionId)}#pub=${encodeURIComponent(pub)}`,
1212
+ apiBase,
1213
+ // Guard against a bogus server TTL: NaN/Infinity/negative would make expiresAt a past
1214
+ // timestamp — or one that NEVER expires (NaN compares false forever), leaving a dead sidecar
1215
+ // that every later invocation resumes until the server 404s.
1216
+ expiresAt: now() + (Number.isFinite(expiresInSec) && expiresInSec > 0 ? expiresInSec : 600) * 1e3
1217
+ };
1218
+ const path = pendingLoginPath();
1219
+ mkdirSync6(dirname6(path), { recursive: true });
1220
+ return withSidecarLock(() => {
1221
+ const winner = loadPendingLoginLocked(now());
1222
+ if (winner) return winner;
1223
+ writeFileSync6(path, JSON.stringify(pending, null, 2), { mode: 384 });
1224
+ chmodSync2(path, 384);
1225
+ return pending;
1226
+ });
1227
+ }
1228
+ var LoginSessionExpiredError = class extends Error {
1229
+ };
1230
+ async function pollLoginSession(pending, opts = {}) {
1231
+ const fetchImpl = opts.fetchImpl ?? fetch;
1232
+ const now = opts.now ?? Date.now;
1233
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1234
+ const deadline = now() + (opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1235
+ const nudgeAt = now() + NUDGE_MS;
1236
+ let nudged = false;
1237
+ let sawOpened = false;
1238
+ while (true) {
1239
+ if (!nudged && !sawOpened && now() >= nudgeAt) {
1240
+ nudged = true;
1241
+ opts.onNudge?.();
1242
+ }
1243
+ if (now() >= pending.expiresAt) {
1244
+ await clearPendingLoginFor(pending.sessionId);
1245
+ throw new LoginSessionExpiredError("the sign-in link expired \u2014 run the command again for a fresh one");
1246
+ }
1247
+ if (now() >= deadline) throw new Error("login timed out \u2014 no response from the browser");
1248
+ let res;
1249
+ try {
1250
+ res = await fetchImpl(`${pending.apiBase}/api/v1/cli-login/${encodeURIComponent(pending.sessionId)}`, {
1251
+ method: "GET",
1252
+ // The poll credential rides a header (never a URL, so never an access log) — see
1253
+ // PendingLogin.pollToken: the session id alone must not read or destroy the handoff.
1254
+ headers: { "x-inplan-poll-token": pending.pollToken },
1255
+ // Capped to the REMAINING deadline: an in-flight request must not let the foreground
1256
+ // wait overrun its budget by a whole request-timeout.
1257
+ signal: AbortSignal.timeout(Math.max(1, Math.min(REQUEST_TIMEOUT_MS, deadline - now())))
1119
1258
  });
1120
- req.on("end", () => {
1121
- if (tooBig) {
1122
- res.writeHead(413).end();
1123
- return;
1124
- }
1125
- let parsed;
1259
+ } catch {
1260
+ await sleep(POLL_MS);
1261
+ continue;
1262
+ }
1263
+ if (res.status === 404) {
1264
+ await clearPendingLoginFor(pending.sessionId);
1265
+ throw new LoginSessionExpiredError("the sign-in link expired \u2014 run the command again for a fresh one");
1266
+ }
1267
+ if (res.ok) {
1268
+ let body;
1269
+ try {
1270
+ body = await res.json();
1271
+ } catch {
1272
+ await sleep(POLL_MS);
1273
+ continue;
1274
+ }
1275
+ if (body.status === "completed" && body.epk && body.iv && body.ct) {
1276
+ let auth;
1126
1277
  try {
1127
- parsed = JSON.parse(body);
1278
+ auth = await unsealHandoff(pending.privateKeyPkcs8, { epk: body.epk, iv: body.iv, ct: body.ct });
1128
1279
  } catch {
1129
- res.writeHead(400).end();
1130
- return;
1280
+ await clearPendingLoginFor(pending.sessionId);
1281
+ throw new LoginSessionExpiredError("the sign-in handoff could not be read \u2014 run the command again for a fresh link");
1131
1282
  }
1132
- if (!isHandoff(parsed) || parsed.state !== state) {
1133
- res.writeHead(403).end();
1134
- return;
1135
- }
1136
- res.writeHead(200, { "content-type": "text/plain" }).end("inplan: signed in \u2014 you can close this tab.");
1137
- const { url: projUrl, anon, refresh, email } = parsed;
1138
- finish(() => resolve4({ url: projUrl, anonKey: anon, refreshToken: refresh, ...email ? { email } : {} }));
1139
- });
1140
- });
1141
- server.on("error", (err) => finish(() => reject(err)));
1142
- const timer = setTimeout(() => finish(() => reject(new Error("login timed out \u2014 no response from the browser"))), timeoutMs);
1143
- if (typeof timer.unref === "function") timer.unref();
1144
- server.listen(0, "127.0.0.1", () => {
1145
- const { port } = server.address();
1146
- const target = `${webOrigin}/cli-auth?port=${port}&state=${state}`;
1147
- opts.onUrl?.(target);
1148
- open(target);
1283
+ await clearPendingLoginFor(pending.sessionId);
1284
+ return auth;
1285
+ }
1286
+ if (body.status === "opened" || body.status === "completed") sawOpened = true;
1287
+ }
1288
+ await sleep(POLL_MS);
1289
+ }
1290
+ }
1291
+ async function rendezvousLogin(opts = {}) {
1292
+ const pending = await createLoginSession(opts);
1293
+ opts.onUrl?.(pending.url);
1294
+ (opts.open ?? openInBrowser)(pending.url);
1295
+ return pollLoginSession(pending, opts);
1296
+ }
1297
+ function openInBrowser(url) {
1298
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1299
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
1300
+ try {
1301
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
1302
+ child.on("error", () => {
1149
1303
  });
1150
- });
1304
+ child.unref();
1305
+ } catch {
1306
+ }
1307
+ }
1308
+ async function unsealHandoff(privateKeyPkcs8, sealed) {
1309
+ const privateKey = await subtle.importKey("pkcs8", Buffer.from(privateKeyPkcs8, "base64"), { name: "ECDH", namedCurve: "P-256" }, false, [
1310
+ "deriveBits"
1311
+ ]);
1312
+ const epk = await subtle.importKey("spki", Buffer.from(sealed.epk, "base64"), { name: "ECDH", namedCurve: "P-256" }, false, []);
1313
+ const shared = await subtle.deriveBits({ name: "ECDH", public: epk }, privateKey, 256);
1314
+ const hkdfKey = await subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
1315
+ const aes = await subtle.deriveKey(
1316
+ { name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: new TextEncoder().encode(HKDF_INFO) },
1317
+ hkdfKey,
1318
+ { name: "AES-GCM", length: 256 },
1319
+ false,
1320
+ ["decrypt"]
1321
+ );
1322
+ const pt = await subtle.decrypt({ name: "AES-GCM", iv: Buffer.from(sealed.iv, "base64") }, aes, Buffer.from(sealed.ct, "base64"));
1323
+ const parsed = JSON.parse(new TextDecoder().decode(pt));
1324
+ if (typeof parsed.url !== "string" || typeof parsed.anon !== "string" || typeof parsed.refresh !== "string") {
1325
+ throw new Error("sign-in handoff was malformed");
1326
+ }
1327
+ return { url: parsed.url, anonKey: parsed.anon, refreshToken: parsed.refresh, ...parsed.email ? { email: parsed.email } : {} };
1151
1328
  }
1152
1329
 
1153
1330
  // src/cliProfile.ts
1154
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "fs";
1155
- import { homedir as homedir4 } from "os";
1156
- import { dirname as dirname6, join as join6 } from "path";
1331
+ import { existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync7 } from "fs";
1332
+ import { homedir as homedir6 } from "os";
1333
+ import { dirname as dirname7, join as join8 } from "path";
1157
1334
  function profilePath() {
1158
- const base2 = process.env.INPLAN_HOME || join6(homedir4(), ".inplan");
1159
- return join6(base2, "profile.json");
1335
+ const base2 = process.env.INPLAN_HOME || join8(homedir6(), ".inplan");
1336
+ return join8(base2, "profile.json");
1160
1337
  }
1161
1338
  function readLocalProfile() {
1162
1339
  const p = profilePath();
1163
- if (!existsSync8(p)) return null;
1340
+ if (!existsSync9(p)) return null;
1164
1341
  try {
1165
- const raw = JSON.parse(readFileSync7(p, "utf8"));
1342
+ const raw = JSON.parse(readFileSync8(p, "utf8"));
1166
1343
  if (typeof raw.name !== "string" || raw.name.trim() === "") return null;
1167
1344
  const source = raw.source === "cloud" || raw.source === "git" ? raw.source : "manual";
1168
1345
  return { name: raw.name.trim(), ...raw.email ? { email: raw.email } : {}, source };
@@ -1172,8 +1349,8 @@ function readLocalProfile() {
1172
1349
  }
1173
1350
  function writeLocalProfile(p) {
1174
1351
  const path = profilePath();
1175
- mkdirSync6(dirname6(path), { recursive: true });
1176
- writeFileSync6(path, `${JSON.stringify(p, null, 2)}
1352
+ mkdirSync7(dirname7(path), { recursive: true });
1353
+ writeFileSync7(path, `${JSON.stringify(p, null, 2)}
1177
1354
  `);
1178
1355
  }
1179
1356
  function setManualProfile(name, email) {
@@ -1198,7 +1375,7 @@ async function resolveIdentity(file) {
1198
1375
  }
1199
1376
  }
1200
1377
  if (file) {
1201
- const git = gitIdentity(dirname6(file));
1378
+ const git = gitIdentity(dirname7(file));
1202
1379
  if (git) {
1203
1380
  const prof = fromParts(git, "git");
1204
1381
  if (prof) {
@@ -1429,48 +1606,6 @@ function addComment(currentText, input) {
1429
1606
  return { text: serialize(next), comment };
1430
1607
  }
1431
1608
 
1432
- // src/pluginGate.ts
1433
- import { homedir as homedir5 } from "os";
1434
- import { join as join7 } from "path";
1435
- import { pathToFileURL } from "url";
1436
- var DEFAULT_HUB_URL = "wss://inplan-collab.fly.dev";
1437
- var resolveHubUrl = () => process.env.INPLAN_PLUGIN_URL || process.env.INPLAN_COLLAB_URL || DEFAULT_HUB_URL;
1438
- var PLUGIN_HTTP = resolveHubUrl().replace(/^ws/, "http");
1439
- var defaultCacheDir = () => join7(process.env.INPLAN_HOME || join7(homedir5(), ".inplan"), "plugin-cache");
1440
- var defaultDeps = {
1441
- resolve: resolvePluginOutcome,
1442
- importCli: (p) => import(pathToFileURL(p).href)
1443
- };
1444
- async function loadPluginGateOutcome(session, options, deps = defaultDeps) {
1445
- try {
1446
- const { plugin, reason } = await deps.resolve({
1447
- apiBase: options.apiBase ?? PLUGIN_HTTP,
1448
- token: options.token,
1449
- cacheDir: options.cacheDir ?? defaultCacheDir(),
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 } : {}
1455
- });
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" };
1460
- const cli = await deps.importCli(cliPath);
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;
1469
- } catch {
1470
- return null;
1471
- }
1472
- }
1473
-
1474
1609
  // src/liveSync.ts
1475
1610
  function shouldHydrateWorkFile(o) {
1476
1611
  if (!o.exists) return true;
@@ -1579,9 +1714,58 @@ var defaultActionable = (e) => e.actor === "user";
1579
1714
  function wakePredicate(wake) {
1580
1715
  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;
1581
1716
  }
1717
+ var REOPEN_GRACE_MS = 3 * 6e4;
1718
+ async function awaitReopen(channel, cursor, opts = {}) {
1719
+ const graceMs = opts.graceMs ?? REOPEN_GRACE_MS;
1720
+ const pollMs = opts.pollMs ?? 2e3;
1721
+ const now = opts.now ?? Date.now;
1722
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1723
+ const deadline = now() + graceMs;
1724
+ const graceStart = now();
1725
+ const budget = () => Math.max(1, Math.min(opts.probeTimeoutMs ?? 1e4, deadline - now()));
1726
+ const supersede = inFlightGate();
1727
+ const reads = inFlightGate();
1728
+ const presences = inFlightGate();
1729
+ let probeCursor = cursor;
1730
+ const seen = [];
1731
+ while (now() < deadline) {
1732
+ if (opts.token && !supersede.busy()) {
1733
+ try {
1734
+ if (await supersede.run(() => channel.isSuperseded(opts.token), budget())) return { kind: "superseded" };
1735
+ } catch {
1736
+ }
1737
+ }
1738
+ if (!reads.busy()) {
1739
+ try {
1740
+ const { entries, cursor: readCursor } = await reads.run(() => channel.readSince(probeCursor), budget());
1741
+ probeCursor = readCursor;
1742
+ seen.push(...entries);
1743
+ const closed = entries.find((e) => {
1744
+ if (e.type !== LogEventType.SessionClosed) return false;
1745
+ const reason = e.payload?.reason;
1746
+ return reason !== void 0 && reason !== "window_closed";
1747
+ });
1748
+ if (closed) {
1749
+ const reason = closed.payload?.reason ?? "completed";
1750
+ return { kind: "completed", cursor: readCursor, entries: seen, reason };
1751
+ }
1752
+ if (entries.some((e) => e.actor === "user" && e.type !== LogEventType.SessionClosed)) return { kind: "reopened" };
1753
+ } catch {
1754
+ }
1755
+ }
1756
+ if (!presences.busy()) {
1757
+ try {
1758
+ if (await presences.run(() => channel.presence(graceStart), budget())) return { kind: "reopened" };
1759
+ } catch {
1760
+ }
1761
+ }
1762
+ await sleep(Math.max(1, Math.min(pollMs, deadline - now())));
1763
+ }
1764
+ return { kind: "expired" };
1765
+ }
1582
1766
  function waitForActions(opts) {
1583
- const debounceMs2 = opts.debounceMs ?? 3e3;
1584
- const pollMs2 = opts.pollMs ?? 200;
1767
+ const debounceMs = opts.debounceMs ?? 3e3;
1768
+ const pollMs = opts.pollMs ?? 200;
1585
1769
  const isActionable = opts.isActionable ?? defaultActionable;
1586
1770
  const watchEditor = opts.watchEditor ?? true;
1587
1771
  const errorGraceMs = opts.errorGraceMs ?? DEFAULT_ERROR_GRACE_MS;
@@ -1650,7 +1834,7 @@ function waitForActions(opts) {
1650
1834
  if (entries.some(isActionable)) {
1651
1835
  if (entries.length !== lastCount) {
1652
1836
  lastCount = entries.length;
1653
- deadline = Date.now() + debounceMs2;
1837
+ deadline = Date.now() + debounceMs;
1654
1838
  } else if (deadline !== null && Date.now() >= deadline) {
1655
1839
  finish({ entries, cursor });
1656
1840
  }
@@ -1666,26 +1850,26 @@ function waitForActions(opts) {
1666
1850
  busy = false;
1667
1851
  }
1668
1852
  };
1669
- const timer = setInterval(() => void tick(), pollMs2);
1853
+ const timer = setInterval(() => void tick(), pollMs);
1670
1854
  opts.signal?.addEventListener("abort", onAbort);
1671
1855
  void tick();
1672
1856
  });
1673
1857
  }
1674
1858
 
1675
1859
  // src/version.ts
1676
- import { readFileSync as readFileSync8 } from "fs";
1677
- import { dirname as dirname7, join as join8 } from "path";
1860
+ import { readFileSync as readFileSync9 } from "fs";
1861
+ import { dirname as dirname8, join as join9 } from "path";
1678
1862
  import { fileURLToPath } from "url";
1679
1863
  function versionFromDir(moduleDir) {
1680
1864
  try {
1681
- const pkg = JSON.parse(readFileSync8(join8(moduleDir, "..", "package.json"), "utf8"));
1865
+ const pkg = JSON.parse(readFileSync9(join9(moduleDir, "..", "package.json"), "utf8"));
1682
1866
  return typeof pkg.version === "string" ? pkg.version : "0.0.0";
1683
1867
  } catch {
1684
1868
  return "0.0.0";
1685
1869
  }
1686
1870
  }
1687
1871
  function versionFromModule(moduleUrl) {
1688
- return versionFromDir(dirname7(fileURLToPath(moduleUrl)));
1872
+ return versionFromDir(dirname8(fileURLToPath(moduleUrl)));
1689
1873
  }
1690
1874
 
1691
1875
  // src/relayActivity.ts
@@ -1706,12 +1890,12 @@ function toolActivityText(toolName, toolInput) {
1706
1890
  }
1707
1891
 
1708
1892
  // src/ensureDoc.ts
1709
- import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "fs";
1710
- import { dirname as dirname8 } from "path";
1893
+ import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync8 } from "fs";
1894
+ import { dirname as dirname9 } from "path";
1711
1895
  function ensureDocFile(file) {
1712
- mkdirSync7(dirname8(file), { recursive: true });
1896
+ mkdirSync8(dirname9(file), { recursive: true });
1713
1897
  try {
1714
- writeFileSync7(file, "", { flag: "wx" });
1898
+ writeFileSync8(file, "", { flag: "wx" });
1715
1899
  return true;
1716
1900
  } catch (err) {
1717
1901
  if (err.code === "EEXIST") return false;
@@ -1777,22 +1961,20 @@ function getFlag(args, name) {
1777
1961
  function hasFlag(args, name) {
1778
1962
  return args.includes(`--${name}`);
1779
1963
  }
1780
- var debounceMs = Number(process.env.INPLAN_DEBOUNCE_MS ?? 3e3);
1781
- var pollMs = Number(process.env.INPLAN_POLL_MS ?? 200);
1782
1964
  function electronDistRel(platform) {
1783
1965
  if (platform === "win32") return "electron.exe";
1784
- if (platform === "darwin") return join9("Electron.app", "Contents", "MacOS", "Electron");
1966
+ if (platform === "darwin") return join10("Electron.app", "Contents", "MacOS", "Electron");
1785
1967
  return "electron";
1786
1968
  }
1787
1969
  function electronBinaryFromDisk(reqUrl) {
1788
1970
  try {
1789
- const pkgDir = dirname9(createRequire(reqUrl).resolve("electron/package.json"));
1971
+ const pkgDir = dirname10(createRequire(reqUrl).resolve("electron/package.json"));
1790
1972
  const rel = electronDistRel(process.platform);
1791
- const bin = join9(pkgDir, "dist", rel);
1792
- if (!existsSync9(bin)) return null;
1973
+ const bin = join10(pkgDir, "dist", rel);
1974
+ if (!existsSync10(bin)) return null;
1793
1975
  try {
1794
- const pathFile = join9(pkgDir, "path.txt");
1795
- if (!existsSync9(pathFile)) writeFileSync8(pathFile, rel);
1976
+ const pathFile = join10(pkgDir, "path.txt");
1977
+ if (!existsSync10(pathFile)) writeFileSync9(pathFile, rel);
1796
1978
  } catch {
1797
1979
  }
1798
1980
  return bin;
@@ -1801,9 +1983,9 @@ function electronBinaryFromDisk(reqUrl) {
1801
1983
  }
1802
1984
  }
1803
1985
  function electronCacheDir() {
1804
- if (process.platform === "win32") return join9(process.env.LOCALAPPDATA ?? join9(homedir6(), "AppData", "Local"), "electron", "Cache");
1805
- if (process.platform === "darwin") return join9(homedir6(), "Library", "Caches", "electron");
1806
- return join9(process.env.XDG_CACHE_HOME ?? join9(homedir6(), ".cache"), "electron");
1986
+ if (process.platform === "win32") return join10(process.env.LOCALAPPDATA ?? join10(homedir7(), "AppData", "Local"), "electron", "Cache");
1987
+ if (process.platform === "darwin") return join10(homedir7(), "Library", "Caches", "electron");
1988
+ return join10(process.env.XDG_CACHE_HOME ?? join10(homedir7(), ".cache"), "electron");
1807
1989
  }
1808
1990
  function cachedElectronZip(version, platform, arch) {
1809
1991
  const root = electronCacheDir();
@@ -1811,9 +1993,9 @@ function cachedElectronZip(version, platform, arch) {
1811
1993
  try {
1812
1994
  let best = null;
1813
1995
  for (const sub of readdirSync2(root)) {
1814
- const f = join9(root, sub, want);
1815
- if (!existsSync9(f)) continue;
1816
- const mtime = statSync3(f).mtimeMs;
1996
+ const f = join10(root, sub, want);
1997
+ if (!existsSync10(f)) continue;
1998
+ const mtime = statSync4(f).mtimeMs;
1817
1999
  if (!best || mtime > best.mtime) best = { file: f, mtime };
1818
2000
  }
1819
2001
  return best?.file ?? null;
@@ -1832,17 +2014,17 @@ function expandArchiveWindows(zipPath, destDir) {
1832
2014
  function autoInstallElectron(reqUrl) {
1833
2015
  if (process.env.INPLAN_NO_ELECTRON_DOWNLOAD === "1") return false;
1834
2016
  try {
1835
- const pkgDir = dirname9(createRequire(reqUrl).resolve("electron/package.json"));
1836
- const installJs = join9(pkgDir, "install.js");
1837
- if (!existsSync9(installJs)) return false;
2017
+ const pkgDir = dirname10(createRequire(reqUrl).resolve("electron/package.json"));
2018
+ const installJs = join10(pkgDir, "install.js");
2019
+ if (!existsSync10(installJs)) return false;
1838
2020
  process.stderr.write("[inplan] editor runtime missing \u2014 retrying the download \u2026\n");
1839
2021
  execFileSync2(process.execPath, [installJs], { cwd: pkgDir, stdio: "inherit", env: process.env });
1840
2022
  if (electronBinaryFromDisk(reqUrl) !== null) return true;
1841
2023
  if (process.platform === "win32") {
1842
- const { version } = JSON.parse(readFileSync9(join9(pkgDir, "package.json"), "utf8"));
2024
+ const { version } = JSON.parse(readFileSync10(join10(pkgDir, "package.json"), "utf8"));
1843
2025
  const zip = cachedElectronZip(version, "win32", process.env.npm_config_arch || process.arch);
1844
- if (zip && expandArchiveWindows(zip, join9(pkgDir, "dist"))) {
1845
- writeFileSync8(join9(pkgDir, "path.txt"), "electron.exe");
2026
+ if (zip && expandArchiveWindows(zip, join10(pkgDir, "dist"))) {
2027
+ writeFileSync9(join10(pkgDir, "path.txt"), "electron.exe");
1846
2028
  }
1847
2029
  }
1848
2030
  return electronBinaryFromDisk(reqUrl) !== null;
@@ -1851,12 +2033,12 @@ function autoInstallElectron(reqUrl) {
1851
2033
  }
1852
2034
  }
1853
2035
  function resolveBundledApp() {
1854
- const here = dirname9(fileURLToPath2(import.meta.url));
1855
- const appMain = join9(here, "..", "app", "main", "index.cjs");
1856
- if (!existsSync9(appMain)) return { appMain: null };
2036
+ const here = dirname10(fileURLToPath2(import.meta.url));
2037
+ const appMain = join10(here, "..", "app", "main", "index.cjs");
2038
+ if (!existsSync10(appMain)) return { appMain: null };
1857
2039
  try {
1858
2040
  const electron = createRequire(import.meta.url)("electron");
1859
- if (typeof electron === "string" && electron && existsSync9(electron)) return { electron, appMain };
2041
+ if (typeof electron === "string" && electron && existsSync10(electron)) return { electron, appMain };
1860
2042
  } catch {
1861
2043
  }
1862
2044
  const onDisk = electronBinaryFromDisk(import.meta.url);
@@ -1891,7 +2073,7 @@ function spawnApp(file) {
1891
2073
  process.stderr.write("[inplan] no bundled editor (running from source?) \u2014 set INPLAN_APP_CMD to your editor; running headless\n");
1892
2074
  } else {
1893
2075
  trackCli("editor_launch_failed", telemetryOn, { reason: "electron_unavailable" });
1894
- const root = resolve3(dirname9(bundled.appMain), "..", "..");
2076
+ const root = resolve3(dirname10(bundled.appMain), "..", "..");
1895
2077
  process.stderr.write(
1896
2078
  `[inplan] the bundled editor's Electron runtime is unavailable: ${bundled.error}
1897
2079
  \u2192 re-download the binary: npm rebuild electron --prefix "${root}"
@@ -1929,7 +2111,7 @@ function maxSeqFrom(entries) {
1929
2111
  }
1930
2112
  function fsBackend(file) {
1931
2113
  const p = docPaths(file);
1932
- mkdirSync8(p.controlDir, { recursive: true });
2114
+ mkdirSync9(p.controlDir, { recursive: true });
1933
2115
  return {
1934
2116
  channel: new FsControlChannel(p),
1935
2117
  store: new FsDocumentStore(p),
@@ -1994,65 +2176,99 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
1994
2176
  process.exit(0);
1995
2177
  });
1996
2178
  }
1997
- const mode = modeFrom(history);
1998
- const isActionable = wakePredicate(mode.wake);
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}).
2179
+ const debounceMs = Number(process.env.INPLAN_DEBOUNCE_MS ?? 3e3);
2180
+ const pollMs = Number(process.env.INPLAN_POLL_MS ?? 200);
2181
+ let waitCursor = cursor;
2182
+ let historyForMode = history;
2183
+ for (; ; ) {
2184
+ const mode = modeFrom(historyForMode);
2185
+ const isActionable = wakePredicate(mode.wake);
2186
+ const result = await waitForActions({ channel, cursor: waitCursor, debounceMs, pollMs, isActionable, token: lockToken });
2187
+ if (result.failed) {
2188
+ backend.logExit("poll_failed");
2189
+ process.stderr.write(`inplan: lost contact with the document (${result.failed.message}).
2003
2190
  If your session expired, run \`inplan login\` and re-attach.
2004
2191
  `);
2005
- output({ status: "wait_failed", message: result.failed.message });
2006
- exitAfterFlush(EXIT_WAIT_FAILED);
2007
- return "exiting";
2008
- }
2009
- if (result.superseded) {
2010
- backend.logExit("superseded");
2011
- output({ status: "superseded" });
2012
- return "ok";
2013
- }
2014
- if (backend.onSaveLocally && result.entries.some((e) => e.type === LogEventType.SaveLocallyRequested)) {
2015
- backend.logExit("save_locally");
2016
- await backend.onSaveLocally();
2017
- return "ok";
2018
- }
2019
- await channel.setCursor(result.cursor);
2020
- const navEntry = result.entries.find((e) => e.type === LogEventType.NavigatedTo);
2021
- if (navEntry) {
2022
- const path = navEntry.payload?.path;
2023
- backend.logExit("navigated");
2024
- output({ status: "navigated", ...path ? { path } : {}, cursor: result.cursor, closed: false });
2192
+ output({ status: "wait_failed", message: result.failed.message });
2193
+ exitAfterFlush(EXIT_WAIT_FAILED);
2194
+ return "exiting";
2195
+ }
2196
+ if (result.superseded) {
2197
+ backend.logExit("superseded");
2198
+ output({ status: "superseded" });
2199
+ return "ok";
2200
+ }
2201
+ if (backend.onSaveLocally && result.entries.some((e) => e.type === LogEventType.SaveLocallyRequested)) {
2202
+ backend.logExit("save_locally");
2203
+ await backend.onSaveLocally();
2204
+ return "ok";
2205
+ }
2206
+ await channel.setCursor(result.cursor);
2207
+ const navEntry = result.entries.find((e) => e.type === LogEventType.NavigatedTo);
2208
+ if (navEntry) {
2209
+ const path = navEntry.payload?.path;
2210
+ backend.logExit("navigated");
2211
+ output({ status: "navigated", ...path ? { path } : {}, cursor: result.cursor, closed: false });
2212
+ return "ok";
2213
+ }
2214
+ const closeEntry = [...result.entries].reverse().find((e) => e.type === LogEventType.SessionClosed);
2215
+ if (closeEntry && (closeEntry.payload?.reason ?? "completed") === "window_closed") {
2216
+ if (result.entries.some((e) => e.seq > closeEntry.seq && e.actor === "user" && e.type !== LogEventType.SessionClosed)) {
2217
+ process.stderr.write("inplan: the editor closed and is already active again \u2014 resuming the wait.\n");
2218
+ waitCursor = closeEntry.seq;
2219
+ historyForMode = await backend.history();
2220
+ continue;
2221
+ }
2222
+ process.stderr.write("inplan: the editor closed \u2014 often just a page reload. Watching for it to come back\u2026\n");
2223
+ const reopen = await awaitReopen(channel, result.cursor, { token: lockToken });
2224
+ if (reopen.kind === "superseded") {
2225
+ backend.logExit("superseded");
2226
+ output({ status: "superseded" });
2227
+ return "ok";
2228
+ }
2229
+ if (reopen.kind === "completed") {
2230
+ await channel.setCursor(reopen.cursor);
2231
+ backend.logExit(reopen.reason);
2232
+ output({ status: "closed", reason: reopen.reason, cursor: reopen.cursor, closed: true, entries: [...result.entries, ...reopen.entries] });
2233
+ return "ok";
2234
+ }
2235
+ if (reopen.kind === "reopened") {
2236
+ process.stderr.write("inplan: the editor is back \u2014 resuming the wait.\n");
2237
+ waitCursor = result.cursor;
2238
+ historyForMode = await backend.history();
2239
+ continue;
2240
+ }
2241
+ process.stderr.write("inplan: the editor did not come back \u2014 treating the session as closed.\n");
2242
+ }
2243
+ let status;
2244
+ let reason;
2245
+ if (closeEntry) {
2246
+ status = "closed";
2247
+ reason = closeEntry.payload?.reason ?? "completed";
2248
+ } else if (result.editorGone) {
2249
+ status = "closed";
2250
+ reason = "crashed_or_killed";
2251
+ } else {
2252
+ status = mode.locksEditor ? "your_turn" : "activity";
2253
+ }
2254
+ backend.logExit(`status:${status}${reason ? `/${reason}` : ""}`);
2255
+ output({
2256
+ status,
2257
+ mode: mode.cadence,
2258
+ humanLocked: status === "your_turn",
2259
+ // Materialized current settings (global file + this session's settings_changed),
2260
+ // so the agent always has them without scanning the log history.
2261
+ settings: settingsFromEntries(historyForMode),
2262
+ // The canonical name the agent should author comments under (model-qualified
2263
+ // when --model was passed), so presence + authorship stay consistent.
2264
+ agentAuthor: agentAuthorFor(model),
2265
+ ...reason ? { reason } : {},
2266
+ cursor: result.cursor,
2267
+ closed: status === "closed",
2268
+ entries: result.entries
2269
+ });
2025
2270
  return "ok";
2026
2271
  }
2027
- const closeEntry = result.entries.find((e) => e.type === LogEventType.SessionClosed);
2028
- let status;
2029
- let reason;
2030
- if (closeEntry) {
2031
- status = "closed";
2032
- reason = closeEntry.payload?.reason ?? "completed";
2033
- } else if (result.editorGone) {
2034
- status = "closed";
2035
- reason = "crashed_or_killed";
2036
- } else {
2037
- status = mode.locksEditor ? "your_turn" : "activity";
2038
- }
2039
- backend.logExit(`status:${status}${reason ? `/${reason}` : ""}`);
2040
- output({
2041
- status,
2042
- mode: mode.cadence,
2043
- humanLocked: status === "your_turn",
2044
- // Materialized current settings (global file + this session's settings_changed),
2045
- // so the agent always has them without scanning the log history.
2046
- settings: settingsFromEntries(history),
2047
- // The canonical name the agent should author comments under (model-qualified
2048
- // when --model was passed), so presence + authorship stay consistent.
2049
- agentAuthor: agentAuthorFor(model),
2050
- ...reason ? { reason } : {},
2051
- cursor: result.cursor,
2052
- closed: status === "closed",
2053
- entries: result.entries
2054
- });
2055
- return "ok";
2056
2272
  }
2057
2273
  async function doLogin(args) {
2058
2274
  const url = getFlag(args, "url") ?? process.env.INPLAN_SUPABASE_URL;
@@ -2065,8 +2281,45 @@ async function doLogin(args) {
2065
2281
  output({ status: "logged_in", url, ...email ? { email } : {} });
2066
2282
  return;
2067
2283
  }
2284
+ if (loginOptOut(args)) {
2285
+ process.stderr.write("inplan login: non-interactive environment \u2014 pass --url/--anon/--refresh (or the matching INPLAN_* env vars).\n");
2286
+ process.exit(1);
2287
+ }
2288
+ const noBrowserHuman = !canInteractiveLogin(args) && Boolean(process.env.INPLAN_NO_BROWSER) && Boolean(process.stdin.isTTY && process.stdout.isTTY) && !process.env.CI && !isKnownAgentEnv();
2289
+ if (!canInteractiveLogin(args) && !noBrowserHuman || isKnownAgentEnv()) {
2290
+ const pending = await loadPendingLogin();
2291
+ if (pending) {
2292
+ try {
2293
+ process.stderr.write(`inplan: waiting for the pending browser sign-in to finish\u2026
2294
+ ${pending.url}
2295
+ `);
2296
+ const auth = await pollLoginSession(pending, { onNudge: printLoginNudge });
2297
+ saveAuth(auth);
2298
+ await persistCloudIdentity();
2299
+ output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
2300
+ return;
2301
+ } catch (e) {
2302
+ if (!(e instanceof LoginSessionExpiredError)) {
2303
+ process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2304
+ `);
2305
+ process.exit(1);
2306
+ }
2307
+ }
2308
+ }
2309
+ await pendingLoginExit();
2310
+ process.exit(1);
2311
+ }
2312
+ clearPendingLogin();
2068
2313
  try {
2069
- const auth = await defaultBrowserLogin();
2314
+ const auth = noBrowserHuman ? await rendezvousLogin({
2315
+ onUrl: (u) => process.stderr.write(`Open this URL in your browser to sign in:
2316
+ ${u}
2317
+ `),
2318
+ onNudge: printLoginNudge,
2319
+ open: () => {
2320
+ }
2321
+ // INPLAN_NO_BROWSER: never launch one — the printed URL is the flow
2322
+ }) : await defaultRendezvousLogin();
2070
2323
  saveAuth(auth);
2071
2324
  await persistCloudIdentity();
2072
2325
  output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
@@ -2089,39 +2342,128 @@ function canInteractiveLogin(args) {
2089
2342
  if (process.env.CI || process.env.INPLAN_NO_BROWSER) return false;
2090
2343
  return Boolean(process.stdin.isTTY && process.stdout.isTTY);
2091
2344
  }
2092
- async function ensureLoggedIn(args, login = defaultBrowserLogin) {
2345
+ async function ensureLoggedIn(args, login = defaultRendezvousLogin, pendingExit = pendingLoginExit, pollPending = (p) => pollLoginSession(p, { onNudge: printLoginNudge })) {
2093
2346
  if (loadAuth()) return true;
2094
- if (!canInteractiveLogin(args)) return false;
2095
- try {
2096
- process.stderr.write("inplan: not signed in \u2014 opening your browser to sign in\u2026\n");
2097
- saveAuth(await login());
2098
- await persistCloudIdentity();
2099
- return true;
2100
- } catch (e) {
2101
- process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2347
+ if (loginOptOut(args)) return false;
2348
+ const pending = await loadPendingLogin();
2349
+ if (pending) {
2350
+ try {
2351
+ process.stderr.write(`inplan: waiting for the pending browser sign-in to finish\u2026
2352
+ ${pending.url}
2102
2353
  `);
2103
- return false;
2354
+ saveAuth(await pollPending(pending));
2355
+ await persistCloudIdentity();
2356
+ return true;
2357
+ } catch (e) {
2358
+ if (!(e instanceof LoginSessionExpiredError)) {
2359
+ process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2360
+ `);
2361
+ return false;
2362
+ }
2363
+ }
2364
+ }
2365
+ if (canInteractiveLogin(args) && !isKnownAgentEnv()) {
2366
+ try {
2367
+ process.stderr.write("inplan: not signed in \u2014 opening your browser to sign in\u2026\n");
2368
+ saveAuth(await login());
2369
+ await persistCloudIdentity();
2370
+ return true;
2371
+ } catch (e) {
2372
+ process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2373
+ `);
2374
+ return false;
2375
+ }
2104
2376
  }
2377
+ await pendingExit();
2378
+ return false;
2379
+ }
2380
+ function loginOptOut(args) {
2381
+ return hasFlag(args, "no-login") || Boolean(process.env.CI);
2105
2382
  }
2106
- function defaultBrowserLogin() {
2107
- return browserLogin({ onUrl: (u) => process.stderr.write(`Opening your browser to sign in:
2383
+ function defaultRendezvousLogin() {
2384
+ return rendezvousLogin({
2385
+ onUrl: (u) => process.stderr.write(`Opening your browser to sign in:
2108
2386
  ${u}
2109
2387
  If it didn't open, paste that URL into your browser.
2110
- `) });
2388
+ `),
2389
+ onNudge: printLoginNudge
2390
+ });
2391
+ }
2392
+ function printLoginNudge() {
2393
+ process.stderr.write("inplan: still waiting \u2014 the browser may not have opened. Open the sign-in URL above manually to continue.\n");
2394
+ }
2395
+ var AGENT_ENV_VARS = ["CLAUDECODE", "CODEX_SANDBOX", "PI_CODING_AGENT", "INPLAN_AGENT"];
2396
+ var AGENT_ENV_PREFIXES = ["CLAUDE_CODE_"];
2397
+ function isKnownAgentEnv(env = process.env) {
2398
+ return AGENT_ENV_VARS.some((k) => Boolean(env[k])) || Object.keys(env).some((k) => AGENT_ENV_PREFIXES.some((p) => k.startsWith(p)));
2399
+ }
2400
+ function scrubAgentEnv(env) {
2401
+ const out = { ...env };
2402
+ for (const k of Object.keys(out)) {
2403
+ if (AGENT_ENV_VARS.includes(k) || AGENT_ENV_PREFIXES.some((p) => k.startsWith(p))) delete out[k];
2404
+ }
2405
+ return out;
2406
+ }
2407
+ async function pendingLoginExit() {
2408
+ let url;
2409
+ let expiresInSec;
2410
+ try {
2411
+ const pending = await createLoginSession();
2412
+ url = pending.url;
2413
+ expiresInSec = Math.max(0, Math.floor((pending.expiresAt - Date.now()) / 1e3));
2414
+ } catch (e) {
2415
+ process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2416
+ `);
2417
+ return;
2418
+ }
2419
+ const quoted = (a) => {
2420
+ if (/^[A-Za-z0-9_@%+=:,.\/-]+$/.test(a)) return a;
2421
+ return process.platform === "win32" ? `"${a.replaceAll('"', '""')}"` : shellQuote(a);
2422
+ };
2423
+ const argsSansCredentials = [];
2424
+ const skipValueOf = /* @__PURE__ */ new Set(["--refresh", "--anon", "--url"]);
2425
+ const argv = process.argv.slice(2);
2426
+ for (let i = 0; i < argv.length; i++) {
2427
+ const a = argv[i];
2428
+ if (skipValueOf.has(a)) {
2429
+ if (i + 1 < argv.length && !argv[i + 1].startsWith("--")) i++;
2430
+ continue;
2431
+ }
2432
+ if ([...skipValueOf].some((f) => a.startsWith(`${f}=`))) continue;
2433
+ argsSansCredentials.push(a);
2434
+ }
2435
+ const entry = process.argv[1] ?? "";
2436
+ const invokedAsInplan = entry.split(/[\\/]/).pop()?.replace(/\.(cmd|ps1)$/i, "") === "inplan";
2437
+ const argv0 = invokedAsInplan ? ["inplan"] : [quoted(process.execPath), quoted(entry)];
2438
+ const resume = [...argv0, ...argsSansCredentials.map(quoted)].join(" ");
2439
+ process.stderr.write(
2440
+ `inplan: sign-in required.
2441
+ ACTION (human): open this URL in a browser and sign in:
2442
+ ${url}
2443
+ NEXT STEP (coding agent): show that URL to the human, then immediately RE-RUN the
2444
+ command you just ran (\`${resume}\`) \u2014 it waits for the sign-in to finish, then continues.
2445
+ The link expires in ${Math.max(1, Math.round(expiresInSec / 60))} minutes.
2446
+ `
2447
+ );
2448
+ output({ status: "login_required", url, resume, expiresInSec });
2449
+ exitAfterFlush(EXIT_LOGIN_PENDING);
2450
+ await new Promise(() => {
2451
+ });
2111
2452
  }
2112
2453
  function stalenessCache() {
2113
- const path = join9(sidecarRoot(), ".update-check.json");
2454
+ const path = join10(sidecarRoot(), ".update-check.json");
2114
2455
  return {
2115
- readCache: () => existsSync9(path) ? readFileSync9(path, "utf8") : null,
2456
+ readCache: () => existsSync10(path) ? readFileSync10(path, "utf8") : null,
2116
2457
  writeCache: (v) => {
2117
- mkdirSync8(dirname9(path), { recursive: true });
2118
- writeFileSync8(path, v);
2458
+ mkdirSync9(dirname10(path), { recursive: true });
2459
+ writeFileSync9(path, v);
2119
2460
  }
2120
2461
  };
2121
2462
  }
2122
2463
  var EXIT_UPGRADE_REQUIRED = 4;
2123
2464
  var EXIT_PLUGIN_UNAVAILABLE = 5;
2124
2465
  var EXIT_WAIT_FAILED = 6;
2466
+ var EXIT_LOGIN_PENDING = 7;
2125
2467
  function shellQuote(path) {
2126
2468
  return "'" + path.replaceAll("'", "'\\''") + "'";
2127
2469
  }
@@ -2188,12 +2530,12 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2188
2530
  }
2189
2531
  const presence = announcePresence(docId, backend.token, model);
2190
2532
  try {
2191
- const workFile = join9(sidecarRoot(), "remote", `${docId}.plan.md`);
2533
+ const workFile = join10(sidecarRoot(), "remote", `${docId}.plan.md`);
2192
2534
  const pendingPath = `${workFile}.pending`;
2193
2535
  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));
2536
+ mkdirSync9(dirname10(workFile), { recursive: true });
2537
+ const readIf = (p) => existsSync10(p) ? readFileSync10(p, "utf8") : null;
2538
+ const recordSynced = (content) => writeFileSync9(hashPath, hashBody(content));
2197
2539
  let canonical = "";
2198
2540
  try {
2199
2541
  canonical = await gate.readCanonical();
@@ -2204,14 +2546,14 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2204
2546
  exitAfterFlush(EXIT_PLUGIN_UNAVAILABLE);
2205
2547
  return;
2206
2548
  }
2207
- const exists = existsSync9(workFile);
2549
+ const exists = existsSync10(workFile);
2208
2550
  if (shouldHydrateWorkFile({
2209
2551
  exists,
2210
- pending: existsSync9(pendingPath),
2211
- currentHash: exists ? hashBody(readFileSync9(workFile, "utf8")) : null,
2552
+ pending: existsSync10(pendingPath),
2553
+ currentHash: exists ? hashBody(readFileSync10(workFile, "utf8")) : null,
2212
2554
  syncedHash: readIf(hashPath)
2213
2555
  })) {
2214
- writeFileSync8(workFile, canonical);
2556
+ writeFileSync9(workFile, canonical);
2215
2557
  recordSynced(canonical);
2216
2558
  }
2217
2559
  const localStore = fsBackend(workFile).store;
@@ -2227,7 +2569,7 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2227
2569
  };
2228
2570
  const onSaveLocallyGate = localFile ? async () => {
2229
2571
  const body = await gate.readCanonical();
2230
- writeFileSync8(localFile, body);
2572
+ writeFileSync9(localFile, body);
2231
2573
  writeStatus(docPaths(localFile).statusPath, { location: "local", originalPath: localFile, lastSyncedHash: hashBody(body) });
2232
2574
  const pid = spawnApp(localFile);
2233
2575
  output({ status: "moved_local", path: localFile, reopened: pid !== null });
@@ -2261,15 +2603,15 @@ async function runRemote(cmd, docId, explicitCursor, confirmed, rest, localFile,
2261
2603
  if (action === "stop") return;
2262
2604
  if (action === "keep-local") {
2263
2605
  if (pendingRequiresReplay({ readFailed: tracked.readFailed(), writeFailed: tracked.writeFailed() })) {
2264
- writeFileSync8(pendingPath, "1");
2606
+ writeFileSync9(pendingPath, "1");
2265
2607
  }
2266
2608
  process.stderr.write("inplan: hub was unavailable this turn \u2014 keeping local edits (will sync next turn)\n");
2267
2609
  } else {
2268
- if (existsSync9(pendingPath)) rmSync2(pendingPath);
2269
- recordSynced(readFileSync9(workFile, "utf8"));
2610
+ if (existsSync10(pendingPath)) rmSync2(pendingPath);
2611
+ recordSynced(readFileSync10(workFile, "utf8"));
2270
2612
  try {
2271
2613
  const fresh = await gate.readCanonical();
2272
- writeFileSync8(workFile, fresh);
2614
+ writeFileSync9(workFile, fresh);
2273
2615
  recordSynced(fresh);
2274
2616
  } catch {
2275
2617
  }
@@ -2288,7 +2630,7 @@ function doPromote(file, args) {
2288
2630
  process.stderr.write("usage: inplan promote <file> --cloud-doc <docId> [--locator org/repo/path]\n");
2289
2631
  process.exit(64);
2290
2632
  }
2291
- const body = existsSync9(file) ? readFileSync9(file, "utf8") : "";
2633
+ const body = existsSync10(file) ? readFileSync10(file, "utf8") : "";
2292
2634
  const status = { location: "cloud", cloudDocId, originalPath: file, lastSyncedHash: hashBody(body) };
2293
2635
  const locator = getFlag(args, "locator");
2294
2636
  if (locator) {
@@ -2333,7 +2675,7 @@ async function doDemote(file, args) {
2333
2675
  return;
2334
2676
  }
2335
2677
  const body = choice.use === "hub" ? hubBody : await backend.store.loadDoc();
2336
- writeFileSync8(dest, body);
2678
+ writeFileSync9(dest, body);
2337
2679
  writeStatus(p.statusPath, { location: "local", originalPath: dest, lastSyncedHash: hashBody(body) });
2338
2680
  output({ status: "demoted", location: "local", path: dest, source: choice.use });
2339
2681
  }
@@ -2368,16 +2710,16 @@ async function doToken() {
2368
2710
  function bundledSkillPath() {
2369
2711
  try {
2370
2712
  const override = process.env.INPLAN_SKILL_SRC;
2371
- if (override) return existsSync9(override) ? override : null;
2372
- const p = join9(dirname9(fileURLToPath2(import.meta.url)), "..", "skill", "SKILL.md");
2373
- return existsSync9(p) ? p : null;
2713
+ if (override) return existsSync10(override) ? override : null;
2714
+ const p = join10(dirname10(fileURLToPath2(import.meta.url)), "..", "skill", "SKILL.md");
2715
+ return existsSync10(p) ? p : null;
2374
2716
  } catch {
2375
2717
  return null;
2376
2718
  }
2377
2719
  }
2378
2720
  function activeDocForCwd(cwd) {
2379
2721
  const root = sidecarRoot();
2380
- if (!existsSync9(root)) return null;
2722
+ if (!existsSync10(root)) return null;
2381
2723
  const real = (p) => {
2382
2724
  try {
2383
2725
  return realpathSync(p);
@@ -2389,13 +2731,13 @@ function activeDocForCwd(cwd) {
2389
2731
  let best = null;
2390
2732
  for (const entry of readdirSync2(root)) {
2391
2733
  try {
2392
- const dir = join9(root, entry);
2393
- const orig = readStatus(join9(dir, "status.json")).originalPath;
2734
+ const dir = join10(root, entry);
2735
+ const orig = readStatus(join10(dir, "status.json")).originalPath;
2394
2736
  if (!orig) continue;
2395
2737
  const rel = relative4(base2, real(orig));
2396
2738
  if (rel === "" || rel.startsWith("..") || isAbsolute2(rel)) continue;
2397
- const logPath = join9(dir, "log.jsonl");
2398
- const mtime = existsSync9(logPath) ? statSync3(logPath).mtimeMs : 0;
2739
+ const logPath = join10(dir, "log.jsonl");
2740
+ const mtime = existsSync10(logPath) ? statSync4(logPath).mtimeMs : 0;
2399
2741
  if (!best || mtime > best.mtime) best = { file: resolve3(orig), mtime };
2400
2742
  } catch {
2401
2743
  }
@@ -2404,11 +2746,11 @@ function activeDocForCwd(cwd) {
2404
2746
  }
2405
2747
  function relayCursorPath(sessionKey) {
2406
2748
  const id = createHash4("sha1").update(sessionKey).digest("hex").slice(0, 16);
2407
- return join9(sidecarRoot(), ".relay-cursors", `${id}.json`);
2749
+ return join10(sidecarRoot(), ".relay-cursors", `${id}.json`);
2408
2750
  }
2409
2751
  function readRelayCursor(sessionKey) {
2410
2752
  try {
2411
- const v = JSON.parse(readFileSync9(relayCursorPath(sessionKey), "utf8"));
2753
+ const v = JSON.parse(readFileSync10(relayCursorPath(sessionKey), "utf8"));
2412
2754
  return typeof v.sent === "number" && v.sent >= 0 ? v.sent : 0;
2413
2755
  } catch {
2414
2756
  return 0;
@@ -2417,8 +2759,8 @@ function readRelayCursor(sessionKey) {
2417
2759
  function writeRelayCursor(sessionKey, sent) {
2418
2760
  try {
2419
2761
  const p = relayCursorPath(sessionKey);
2420
- mkdirSync8(dirname9(p), { recursive: true });
2421
- writeFileSync8(p, JSON.stringify({ sent }) + "\n");
2762
+ mkdirSync9(dirname10(p), { recursive: true });
2763
+ writeFileSync9(p, JSON.stringify({ sent }) + "\n");
2422
2764
  } catch {
2423
2765
  }
2424
2766
  }
@@ -2426,7 +2768,7 @@ function transcriptTextBlocks(path) {
2426
2768
  const out = [];
2427
2769
  let raw;
2428
2770
  try {
2429
- raw = readFileSync9(path, "utf8");
2771
+ raw = readFileSync10(path, "utf8");
2430
2772
  } catch {
2431
2773
  return out;
2432
2774
  }
@@ -2471,7 +2813,7 @@ function notesFromHook(kind, stdin, argv) {
2471
2813
  const p = parse2(stdin);
2472
2814
  const transcript = str(p.transcript_path);
2473
2815
  const sessionKey = str(p.session_id) || transcript;
2474
- const blocks = transcript && existsSync9(transcript) && sessionKey ? transcriptTextBlocks(transcript) : [];
2816
+ const blocks = transcript && existsSync10(transcript) && sessionKey ? transcriptTextBlocks(transcript) : [];
2475
2817
  if (blocks.length > 0) {
2476
2818
  const sent = readRelayCursor(sessionKey);
2477
2819
  for (let i = Math.max(0, sent); i < blocks.length; i++) notes.push(blocks[i]);
@@ -2495,7 +2837,7 @@ async function relayText(file, text) {
2495
2837
  await backend.channel.append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
2496
2838
  } else if (route.kind === "local") {
2497
2839
  const p = docPaths(file);
2498
- mkdirSync8(p.controlDir, { recursive: true });
2840
+ mkdirSync9(p.controlDir, { recursive: true });
2499
2841
  await new FsControlChannel(p).append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
2500
2842
  }
2501
2843
  } catch {
@@ -2513,7 +2855,7 @@ async function doRelay(args) {
2513
2855
  let stdin = "";
2514
2856
  if (hook !== "codex-notify") {
2515
2857
  try {
2516
- stdin = readFileSync9(0, "utf8");
2858
+ stdin = readFileSync10(0, "utf8");
2517
2859
  } catch {
2518
2860
  }
2519
2861
  }
@@ -2531,22 +2873,22 @@ async function doRelay(args) {
2531
2873
  output({ status: "relayed", count: clean.length });
2532
2874
  }
2533
2875
  function skillTargets() {
2534
- const home = homedir6();
2876
+ const home = homedir7();
2535
2877
  return [
2536
- { name: "Claude Code", root: join9(home, ".claude"), target: join9(home, ".claude", "skills", "inplan", "SKILL.md") },
2537
- { name: "Pi", root: join9(home, ".pi", "agent"), target: join9(home, ".pi", "agent", "skills", "inplan", "SKILL.md") },
2538
- { name: "Codex", root: join9(home, ".codex"), target: join9(home, ".codex", "skills", "inplan", "SKILL.md") }
2878
+ { name: "Claude Code", root: join10(home, ".claude"), target: join10(home, ".claude", "skills", "inplan", "SKILL.md") },
2879
+ { name: "Pi", root: join10(home, ".pi", "agent"), target: join10(home, ".pi", "agent", "skills", "inplan", "SKILL.md") },
2880
+ { name: "Codex", root: join10(home, ".codex"), target: join10(home, ".codex", "skills", "inplan", "SKILL.md") }
2539
2881
  ];
2540
2882
  }
2541
2883
  var SKILL_ALLOW = ["Bash(inplan *)", "Edit(**/*.plan.md)", "Read(~/.inplan/**)", "Edit(~/.inplan/**)"];
2542
2884
  var SKILL_ALLOW_OBSOLETE = ["Write(**/*.plan.md)", "Write(~/.inplan/**)"];
2543
2885
  var SKILL_DIRS = ["~/.inplan/"];
2544
2886
  function grantClaudePermissions(claudeRoot) {
2545
- const settingsPath = join9(claudeRoot, "settings.json");
2887
+ const settingsPath = join10(claudeRoot, "settings.json");
2546
2888
  let settings = {};
2547
2889
  try {
2548
- if (existsSync9(settingsPath)) {
2549
- const parsed = JSON.parse(readFileSync9(settingsPath, "utf8"));
2890
+ if (existsSync10(settingsPath)) {
2891
+ const parsed = JSON.parse(readFileSync10(settingsPath, "utf8"));
2550
2892
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
2551
2893
  settings = parsed;
2552
2894
  }
@@ -2579,7 +2921,7 @@ function grantClaudePermissions(claudeRoot) {
2579
2921
  settings.permissions = perms;
2580
2922
  try {
2581
2923
  const tmp = settingsPath + ".tmp";
2582
- writeFileSync8(tmp, JSON.stringify(settings, null, 2) + "\n");
2924
+ writeFileSync9(tmp, JSON.stringify(settings, null, 2) + "\n");
2583
2925
  renameSync2(tmp, settingsPath);
2584
2926
  } catch {
2585
2927
  return false;
@@ -2625,8 +2967,8 @@ function mergeRelayHooks(settings, entries) {
2625
2967
  }
2626
2968
  function readJsonObject(path) {
2627
2969
  try {
2628
- if (!existsSync9(path)) return {};
2629
- const parsed = JSON.parse(readFileSync9(path, "utf8"));
2970
+ if (!existsSync10(path)) return {};
2971
+ const parsed = JSON.parse(readFileSync10(path, "utf8"));
2630
2972
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
2631
2973
  return parsed;
2632
2974
  } catch {
@@ -2635,9 +2977,9 @@ function readJsonObject(path) {
2635
2977
  }
2636
2978
  function writeJsonAtomic(path, value) {
2637
2979
  try {
2638
- mkdirSync8(dirname9(path), { recursive: true });
2980
+ mkdirSync9(dirname10(path), { recursive: true });
2639
2981
  const tmp = path + ".tmp";
2640
- writeFileSync8(tmp, JSON.stringify(value, null, 2) + "\n");
2982
+ writeFileSync9(tmp, JSON.stringify(value, null, 2) + "\n");
2641
2983
  renameSync2(tmp, path);
2642
2984
  return true;
2643
2985
  } catch {
@@ -2645,13 +2987,13 @@ function writeJsonAtomic(path, value) {
2645
2987
  }
2646
2988
  }
2647
2989
  function installClaudeHooks(claudeRoot) {
2648
- const path = join9(claudeRoot, "settings.json");
2990
+ const path = join10(claudeRoot, "settings.json");
2649
2991
  const settings = readJsonObject(path);
2650
2992
  if (!settings || !mergeRelayHooks(settings, CLAUDE_RELAY_HOOKS)) return false;
2651
2993
  return writeJsonAtomic(path, settings);
2652
2994
  }
2653
2995
  function installCodexHooks(codexRoot) {
2654
- const path = join9(codexRoot, "hooks.json");
2996
+ const path = join10(codexRoot, "hooks.json");
2655
2997
  const cfg = readJsonObject(path);
2656
2998
  if (!cfg || !mergeRelayHooks(cfg, CODEX_RELAY_HOOKS)) return false;
2657
2999
  return writeJsonAtomic(path, cfg);
@@ -2701,16 +3043,16 @@ export default function (pi) {
2701
3043
  }
2702
3044
  `;
2703
3045
  function installPiRelayExtension(piAgentRoot) {
2704
- const path = join9(piAgentRoot, "extensions", "inplan-relay.ts");
3046
+ const path = join10(piAgentRoot, "extensions", "inplan-relay.ts");
2705
3047
  try {
2706
- if (existsSync9(path)) {
2707
- const cur = readFileSync9(path, "utf8");
3048
+ if (existsSync10(path)) {
3049
+ const cur = readFileSync10(path, "utf8");
2708
3050
  if (cur === PI_RELAY_EXTENSION) return false;
2709
3051
  if (!cur.startsWith(PI_RELAY_MARKER)) return false;
2710
3052
  }
2711
- mkdirSync8(dirname9(path), { recursive: true });
3053
+ mkdirSync9(dirname10(path), { recursive: true });
2712
3054
  const tmp = path + ".tmp";
2713
- writeFileSync8(tmp, PI_RELAY_EXTENSION);
3055
+ writeFileSync9(tmp, PI_RELAY_EXTENSION);
2714
3056
  renameSync2(tmp, path);
2715
3057
  return true;
2716
3058
  } catch {
@@ -2731,28 +3073,28 @@ function doInstallSkill(args) {
2731
3073
  const installed = [];
2732
3074
  for (const a of skillTargets()) {
2733
3075
  try {
2734
- if (!existsSync9(a.root)) continue;
2735
- if (!existsSync9(a.target)) {
2736
- mkdirSync8(dirname9(a.target), { recursive: true });
3076
+ if (!existsSync10(a.root)) continue;
3077
+ if (!existsSync10(a.target)) {
3078
+ mkdirSync9(dirname10(a.target), { recursive: true });
2737
3079
  copyFileSync(src, a.target);
2738
3080
  installed.push(a.name);
2739
3081
  process.stderr.write(`inplan: installed the inplan skill into ${a.name} (${a.target}). Set INPLAN_NO_SKILL_INSTALL=1 to skip.
2740
3082
  `);
2741
3083
  }
2742
3084
  if (a.name === "Claude Code" && grantClaudePermissions(a.root)) {
2743
- process.stderr.write(`inplan: granted scoped auto-approval (plan files + ~/.inplan + inplan CLI) in ${join9(a.root, "settings.json")}.
3085
+ process.stderr.write(`inplan: granted scoped auto-approval (plan files + ~/.inplan + inplan CLI) in ${join10(a.root, "settings.json")}.
2744
3086
  `);
2745
3087
  }
2746
3088
  if (a.name === "Claude Code" && installClaudeHooks(a.root)) {
2747
- process.stderr.write(`inplan: configured the agent-console relay hooks in ${join9(a.root, "settings.json")}.
3089
+ process.stderr.write(`inplan: configured the agent-console relay hooks in ${join10(a.root, "settings.json")}.
2748
3090
  `);
2749
3091
  }
2750
3092
  if (a.name === "Codex" && installCodexHooks(a.root)) {
2751
- process.stderr.write(`inplan: configured the agent-console relay hooks in ${join9(a.root, "hooks.json")}.
3093
+ process.stderr.write(`inplan: configured the agent-console relay hooks in ${join10(a.root, "hooks.json")}.
2752
3094
  `);
2753
3095
  }
2754
3096
  if (a.name === "Pi" && installPiRelayExtension(a.root)) {
2755
- process.stderr.write(`inplan: installed the agent-console relay extension in ${join9(a.root, "extensions", "inplan-relay.ts")}.
3097
+ process.stderr.write(`inplan: installed the agent-console relay extension in ${join10(a.root, "extensions", "inplan-relay.ts")}.
2756
3098
  `);
2757
3099
  }
2758
3100
  } catch {
@@ -2786,7 +3128,7 @@ async function doUpload(file, args) {
2786
3128
  process.exit(1);
2787
3129
  }
2788
3130
  const org = orgOf(pick);
2789
- const body = existsSync9(file) ? readFileSync9(file, "utf8") : "";
3131
+ const body = existsSync10(file) ? readFileSync10(file, "utf8") : "";
2790
3132
  const prov = gitProvenance(file);
2791
3133
  const repo = getFlag(args, "repo") ?? prov.repo;
2792
3134
  const path = getFlag(args, "path") ?? prov.path;
@@ -2847,8 +3189,8 @@ function routeFor(file, cmd, args) {
2847
3189
  const status = readStatus(p.statusPath);
2848
3190
  if (status.location !== "cloud" || !status.cloudDocId) return { kind: "local" };
2849
3191
  const docId = status.cloudDocId;
2850
- if (cmd === "signal" || cmd === "message" || !existsSync9(file)) return { kind: "cloud", docId };
2851
- const local = readFileSync9(file, "utf8");
3192
+ if (cmd === "signal" || cmd === "message" || !existsSync10(file)) return { kind: "cloud", docId };
3193
+ const local = readFileSync10(file, "utf8");
2852
3194
  const diverged = status.lastSyncedHash !== void 0 && hashBody(local) !== status.lastSyncedHash;
2853
3195
  if (!diverged || hasFlag(args, "use-cloud")) return { kind: "cloud", docId };
2854
3196
  if (hasFlag(args, "continue-locally")) {
@@ -2966,7 +3308,7 @@ async function main() {
2966
3308
  }
2967
3309
  if (cmd === "signal") {
2968
3310
  const p = docPaths(file);
2969
- mkdirSync8(p.controlDir, { recursive: true });
3311
+ mkdirSync9(p.controlDir, { recursive: true });
2970
3312
  const channel = new FsControlChannel(p);
2971
3313
  if (hasFlag(args, "done")) {
2972
3314
  await channel.append({ actor: "agent", type: LogEventType.AgentDoneSuggested });
@@ -2984,13 +3326,13 @@ async function main() {
2984
3326
  process.exit(1);
2985
3327
  }
2986
3328
  const p = docPaths(file);
2987
- mkdirSync8(p.controlDir, { recursive: true });
3329
+ mkdirSync9(p.controlDir, { recursive: true });
2988
3330
  const channel = new FsControlChannel(p);
2989
3331
  await channel.append({ actor: "agent", type: LogEventType.AgentMessage, payload: { text } });
2990
3332
  output({ status: "messaged" });
2991
3333
  return;
2992
3334
  }
2993
- if (cmd !== "open" && !existsSync9(file)) {
3335
+ if (cmd !== "open" && !existsSync10(file)) {
2994
3336
  process.stderr.write(`inplan ${cmd}: file not found: ${file}
2995
3337
  `);
2996
3338
  process.exit(1);
@@ -3016,7 +3358,7 @@ async function main() {
3016
3358
  }
3017
3359
  }
3018
3360
  try {
3019
- const currentText = readFileSync9(file, "utf8");
3361
+ const currentText = readFileSync10(file, "utf8");
3020
3362
  const { text: nextText, comment } = addComment(currentText, {
3021
3363
  text,
3022
3364
  author: agentAuthorFor(model),
@@ -3026,7 +3368,7 @@ async function main() {
3026
3368
  ...question ? { question } : {},
3027
3369
  mayResolve: hasFlag(args, "may-resolve")
3028
3370
  });
3029
- writeFileSync8(file, nextText);
3371
+ writeFileSync9(file, nextText);
3030
3372
  output({ status: "commented", id: comment.id, date: comment.date, author: comment.author });
3031
3373
  } catch (err) {
3032
3374
  if (err instanceof AddCommentError) {
@@ -3041,7 +3383,7 @@ async function main() {
3041
3383
  if (cmd === "open") {
3042
3384
  ensureDocFile(file);
3043
3385
  const p = docPaths(file);
3044
- mkdirSync8(p.controlDir, { recursive: true });
3386
+ mkdirSync9(p.controlDir, { recursive: true });
3045
3387
  const st = readStatus(p.statusPath);
3046
3388
  if (st.location !== "cloud") writeStatus(p.statusPath, { ...st, location: "local", originalPath: file });
3047
3389
  const existing = runningEditorPid(p.logPath);
@@ -3091,6 +3433,9 @@ if (isProgramEntry()) {
3091
3433
  });
3092
3434
  }
3093
3435
  export {
3436
+ AGENT_ENV_PREFIXES,
3437
+ AGENT_ENV_VARS,
3438
+ EXIT_LOGIN_PENDING,
3094
3439
  EXIT_PLUGIN_UNAVAILABLE,
3095
3440
  EXIT_UPGRADE_REQUIRED,
3096
3441
  EXIT_WAIT_FAILED,
@@ -3100,7 +3445,10 @@ export {
3100
3445
  ensureLoggedIn,
3101
3446
  exitAfterFlush,
3102
3447
  explainNoGate,
3448
+ isKnownAgentEnv,
3103
3449
  notesFromHook,
3450
+ scrubAgentEnv,
3104
3451
  shellQuote,
3105
- transcriptTextBlocks
3452
+ transcriptTextBlocks,
3453
+ waitCycle
3106
3454
  };