inplan 0.2.1 → 0.3.0

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
@@ -2332,6 +2332,7 @@ function wakePredicate(wake) {
2332
2332
  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;
2333
2333
  }
2334
2334
  var REOPEN_GRACE_MS = 3 * 6e4;
2335
+ var PRESENCE_GONE_GRACE_MS = 9e4;
2335
2336
  async function awaitReopen(channel, cursor, opts = {}) {
2336
2337
  const graceMs = opts.graceMs ?? REOPEN_GRACE_MS;
2337
2338
  const pollMs = opts.pollMs ?? 2e3;
@@ -2385,6 +2386,7 @@ function waitForActions(opts) {
2385
2386
  const pollMs = opts.pollMs ?? 200;
2386
2387
  const isActionable = opts.isActionable ?? defaultActionable;
2387
2388
  const watchEditor = opts.watchEditor ?? true;
2389
+ const presenceGoneGraceMs = opts.presenceGoneGraceMs ?? PRESENCE_GONE_GRACE_MS;
2388
2390
  const errorGraceMs = opts.errorGraceMs ?? DEFAULT_ERROR_GRACE_MS;
2389
2391
  const pollTimeoutMs = opts.pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS;
2390
2392
  const now = opts.now ?? Date.now;
@@ -2393,6 +2395,7 @@ function waitForActions(opts) {
2393
2395
  let deadline = null;
2394
2396
  let lastCount = -1;
2395
2397
  let sawEditorAlive = false;
2398
+ let goneSince = null;
2396
2399
  let busy = false;
2397
2400
  let done = false;
2398
2401
  let failingSince = null;
@@ -2442,10 +2445,16 @@ function waitForActions(opts) {
2442
2445
  if (!presences.busy()) alive = await presences.run(() => ch.presence(), pollTimeoutMs);
2443
2446
  } catch {
2444
2447
  }
2445
- if (alive === true) sawEditorAlive = true;
2446
- else if (alive === false && sawEditorAlive) {
2447
- finish({ entries, cursor, editorGone: true });
2448
- return;
2448
+ if (alive === true) {
2449
+ sawEditorAlive = true;
2450
+ goneSince = null;
2451
+ } else if (alive === false && sawEditorAlive) {
2452
+ const at = now();
2453
+ goneSince ??= at;
2454
+ if (at - goneSince >= presenceGoneGraceMs) {
2455
+ finish({ entries, cursor, editorGone: true });
2456
+ return;
2457
+ }
2449
2458
  }
2450
2459
  }
2451
2460
  if (entries.some(isActionable)) {
@@ -2749,6 +2758,12 @@ function logWaitExit(p, reason) {
2749
2758
  } catch {
2750
2759
  }
2751
2760
  }
2761
+ function resolveWaitStatus(input) {
2762
+ if (input.closeReason !== null) return { status: "closed", reason: input.closeReason };
2763
+ if (input.editorGone && !input.hasActionable) return { status: "closed", reason: "crashed_or_killed" };
2764
+ if (input.editorGone) return { status: input.locksEditor ? "your_turn" : "activity", editorGone: true };
2765
+ return { status: input.locksEditor ? "your_turn" : "activity" };
2766
+ }
2752
2767
  async function waitCycle(backend, explicitCursor, confirmed, model, gate = null) {
2753
2768
  const { channel, store } = backend;
2754
2769
  const history = await backend.history();
@@ -2889,17 +2904,12 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2889
2904
  }
2890
2905
  process.stderr.write("inplan: the editor did not come back \u2014 treating the session as closed.\n");
2891
2906
  }
2892
- let status;
2893
- let reason;
2894
- if (closeEntry) {
2895
- status = "closed";
2896
- reason = closeEntry.payload?.reason ?? "completed";
2897
- } else if (result.editorGone) {
2898
- status = "closed";
2899
- reason = "crashed_or_killed";
2900
- } else {
2901
- status = mode.locksEditor ? "your_turn" : "activity";
2902
- }
2907
+ const { status, reason, editorGone } = resolveWaitStatus({
2908
+ closeReason: closeEntry ? closeEntry.payload?.reason ?? "completed" : null,
2909
+ editorGone: result.editorGone === true,
2910
+ hasActionable: result.entries.some(isActionable),
2911
+ locksEditor: mode.locksEditor
2912
+ });
2903
2913
  backend.logExit(`status:${status}${reason ? `/${reason}` : ""}`);
2904
2914
  output({
2905
2915
  status,
@@ -2912,6 +2922,12 @@ async function waitCycle(backend, explicitCursor, confirmed, model, gate = null)
2912
2922
  // when --model was passed), so presence + authorship stay consistent.
2913
2923
  agentAuthor: agentAuthorFor(model),
2914
2924
  ...reason ? { reason } : {},
2925
+ // The human handed the turn back and THEN left. Surfaced because the handoff status
2926
+ // deliberately outranks the departure, and dropping the departure entirely would strand the
2927
+ // agent: a fresh `wait` starts with `sawEditorAlive` false, so an editor that is already gone
2928
+ // never flips it and that wait would block instead of reporting the closure. Act on the
2929
+ // handoff, then stop — do not wait again.
2930
+ ...editorGone ? { editorGone: true } : {},
2915
2931
  // The landing signal for a parked Review-mode edit (#88): pending_review means the push
2916
2932
  // REACHED the store and awaits the human — the canonical is unchanged by design. Absent
2917
2933
  // when the turn applied directly (or made no body change).
@@ -4085,15 +4101,10 @@ async function cleanupOrphanedUploads(db, paths) {
4085
4101
  } catch {
4086
4102
  }
4087
4103
  }
4088
- async function doAssetUpload(file, args) {
4089
- const status = readStatus(docPaths(file).statusPath);
4090
- if (status.location !== "cloud" || !status.cloudDocId) {
4091
- process.stderr.write("inplan asset-upload: document is not in the cloud\n");
4092
- process.exit(1);
4093
- }
4104
+ async function doAssetUploadForDoc(cloudDocId, args) {
4094
4105
  const bytesFile = getFlag(args, "bytes-file");
4095
4106
  if (!bytesFile) {
4096
- process.stderr.write("inplan asset-upload: usage: inplan asset-upload <file> --bytes-file <path> [--ext <ext>]\n");
4107
+ process.stderr.write("inplan asset-upload: usage: inplan asset-upload <file|--remote DOC_ID> --bytes-file <path> [--ext <ext>]\n");
4097
4108
  process.exit(64);
4098
4109
  }
4099
4110
  const s = await authedSession();
@@ -4101,7 +4112,7 @@ async function doAssetUpload(file, args) {
4101
4112
  process.stderr.write("inplan: not logged in (or session expired) \u2014 run `inplan login`\n");
4102
4113
  process.exit(1);
4103
4114
  }
4104
- const { data: doc, error: docErr } = await s.db.from("documents").select("org_id").eq("id", status.cloudDocId).maybeSingle();
4115
+ const { data: doc, error: docErr } = await s.db.from("documents").select("org_id").eq("id", cloudDocId).maybeSingle();
4105
4116
  const orgId = doc?.org_id;
4106
4117
  if (docErr || !orgId) {
4107
4118
  process.stderr.write(`inplan asset-upload: ${docErr?.message ?? "could not resolve the document's organization"}
@@ -4110,13 +4121,29 @@ async function doAssetUpload(file, args) {
4110
4121
  }
4111
4122
  const requestedExt = (getFlag(args, "ext") ?? "png").toLowerCase();
4112
4123
  const bytes = readFileSync11(bytesFile);
4113
- const uploaded = await uploadAssetBytes(s.db, orgId, status.cloudDocId, bytes, requestedExt);
4124
+ const storedExt = Object.prototype.hasOwnProperty.call(ASSET_MIME_BY_EXT, requestedExt) ? requestedExt : "png";
4125
+ const sha256 = createHash4("sha256").update(bytes).digest("hex");
4126
+ const known = await assetPathByContent(s.db, cloudDocId, sha256, storedExt);
4127
+ if (known) {
4128
+ output({ status: "uploaded", relPath: s.db.storage.from(ASSET_BUCKET).getPublicUrl(known).data.publicUrl, reused: true });
4129
+ return;
4130
+ }
4131
+ const uploaded = await uploadAssetBytes(s.db, orgId, cloudDocId, bytes, requestedExt);
4114
4132
  if (!uploaded) {
4115
4133
  process.stderr.write("inplan asset-upload: upload failed\n");
4116
4134
  process.exit(1);
4117
4135
  }
4136
+ await rememberAsset(s.db, cloudDocId, sha256, storedExt, uploaded.path);
4118
4137
  output({ status: "uploaded", relPath: uploaded.url });
4119
4138
  }
4139
+ async function doAssetUpload(file, args) {
4140
+ const status = readStatus(docPaths(file).statusPath);
4141
+ if (status.location !== "cloud" || !status.cloudDocId) {
4142
+ process.stderr.write("inplan asset-upload: document is not in the cloud \u2014 for a doc you attached by id, use `inplan asset-upload --remote <docId>`\n");
4143
+ process.exit(1);
4144
+ }
4145
+ await doAssetUploadForDoc(status.cloudDocId, args);
4146
+ }
4120
4147
  var IMAGE_REF_RE = /!\[([^\]]*)\]\(\s*(?:<([^>]+)>|([^()\s]+))\s*\)/g;
4121
4148
  function isLocalRelativePath(dest) {
4122
4149
  return !/^[a-z][a-z0-9+.-]*:/i.test(dest) && !dest.startsWith("//") && !dest.startsWith("/");
@@ -4149,10 +4176,27 @@ function codeRanges(body) {
4149
4176
  function inRange(ranges, index) {
4150
4177
  return ranges.some(([start, end]) => index >= start && index < end);
4151
4178
  }
4179
+ async function assetPathByContent(db, docId, sha256, ext) {
4180
+ try {
4181
+ const { data, error } = await db.from("doc_assets").select("object_path").eq("doc_id", docId).eq("sha256", sha256).eq("ext", ext).maybeSingle();
4182
+ if (error) return null;
4183
+ const path = data?.object_path;
4184
+ return typeof path === "string" && path.length > 0 ? path : null;
4185
+ } catch {
4186
+ return null;
4187
+ }
4188
+ }
4189
+ async function rememberAsset(db, docId, sha256, ext, objectPath) {
4190
+ try {
4191
+ await db.from("doc_assets").insert({ doc_id: docId, sha256, ext, object_path: objectPath });
4192
+ } catch {
4193
+ }
4194
+ }
4152
4195
  async function migrateLocalImages(body, docDir, db, orgId, docId) {
4153
4196
  const excluded = codeRanges(body);
4154
4197
  const migrations = /* @__PURE__ */ new Map();
4155
4198
  const uploadedByDest = /* @__PURE__ */ new Map();
4199
+ const uploadedByHash = /* @__PURE__ */ new Map();
4156
4200
  const uploadedPaths = [];
4157
4201
  let docDirReal;
4158
4202
  try {
@@ -4186,9 +4230,27 @@ async function migrateLocalImages(body, docDir, db, orgId, docId) {
4186
4230
  } catch {
4187
4231
  continue;
4188
4232
  }
4233
+ const sha256 = createHash4("sha256").update(bytes).digest("hex");
4234
+ const contentKey = `${ext}:${sha256}`;
4235
+ const byHash = uploadedByHash.get(contentKey);
4236
+ if (byHash) {
4237
+ uploadedByDest.set(dest, byHash);
4238
+ migrations.set(m.index, { dest, url: byHash.url });
4239
+ continue;
4240
+ }
4241
+ const known = await assetPathByContent(db, docId, sha256, ext);
4242
+ if (known) {
4243
+ const reused = { path: known, url: db.storage.from(ASSET_BUCKET).getPublicUrl(known).data.publicUrl };
4244
+ uploadedByDest.set(dest, reused);
4245
+ uploadedByHash.set(contentKey, reused);
4246
+ migrations.set(m.index, { dest, url: reused.url });
4247
+ continue;
4248
+ }
4189
4249
  const uploaded = await uploadAssetBytes(db, orgId, docId, bytes, ext);
4190
4250
  if (!uploaded) continue;
4251
+ await rememberAsset(db, docId, sha256, ext, uploaded.path);
4191
4252
  uploadedByDest.set(dest, uploaded);
4253
+ uploadedByHash.set(contentKey, uploaded);
4192
4254
  uploadedPaths.push(uploaded.path);
4193
4255
  migrations.set(m.index, { dest, url: uploaded.url });
4194
4256
  }
@@ -4278,7 +4340,7 @@ async function main() {
4278
4340
  );
4279
4341
  if (!cmd || !["open", "wait", "signal", "message", "comment", "relay", "status", "promote", "demote", "upload", "asset-upload"].includes(cmd)) {
4280
4342
  process.stderr.write(
4281
- '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 asset-upload <file> --bytes-file <path> [--ext <ext>] (cloud doc: paste/pick an image straight to storage)\n inplan login (opens the browser to sign in; or --url <url> --anon <key> --refresh <token> for scripts)\n inplan whoami | logout\n'
4343
+ '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 asset-upload <file|--remote DOC_ID> --bytes-file <path> [--ext <ext>] (cloud doc: paste/pick an image straight to storage)\n inplan login (opens the browser to sign in; or --url <url> --anon <key> --refresh <token> for scripts)\n inplan whoami | logout\n'
4282
4344
  );
4283
4345
  process.exit(64);
4284
4346
  }
@@ -4289,6 +4351,10 @@ async function main() {
4289
4351
  const remoteDocId = getFlag(args, "remote");
4290
4352
  if (remoteDocId) {
4291
4353
  rejectCommentOnCloud(cmd, false);
4354
+ if (cmd === "asset-upload") {
4355
+ await doAssetUploadForDoc(remoteDocId, args);
4356
+ return;
4357
+ }
4292
4358
  const remoteCmd = cmd === "open" ? "wait" : cmd;
4293
4359
  if (cmd === "open") {
4294
4360
  process.stderr.write("inplan: `open --remote` is deprecated (a cloud doc has no local editor to launch) \u2014 use `wait --remote`. Attaching as `wait`.\n");
@@ -4474,13 +4540,16 @@ export {
4474
4540
  activeDocForCwd,
4475
4541
  canInteractiveLogin,
4476
4542
  doAssetUpload,
4543
+ doAssetUploadForDoc,
4477
4544
  doUpload,
4478
4545
  ensureLoggedIn,
4479
4546
  exitAfterFlush,
4480
4547
  explainNoGate,
4481
4548
  isKnownAgentEnv,
4549
+ main,
4482
4550
  notesFromHook,
4483
4551
  primeSessionOrFail,
4552
+ resolveWaitStatus,
4484
4553
  scrubAgentEnv,
4485
4554
  shellQuote,
4486
4555
  transcriptTextBlocks,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inplan",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "inplan — a Markdown editor for human ⇄ coding-agent planning. CLI + desktop editor.",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "repository": {
package/skill/SKILL.md CHANGED
@@ -196,6 +196,28 @@ anchored comment is an inline Markdown link whose href is the comment id:
196
196
  mechanism itself and is fine — this is about the surrounding prose.) The body should read as
197
197
  a complete document with every comment stripped out.
198
198
 
199
+ ### Images
200
+
201
+ A plan can carry images, but **the bytes have to reach the document's own storage first** —
202
+ a filename, a local path, or a `scratchpad/` reference renders as a broken image for the
203
+ human, who has no access to your filesystem. Upload, then reference what the upload prints:
204
+
205
+ $ inplan asset-upload --remote <docId> --bytes-file ./shot.png --ext png
206
+ {"status":"uploaded","relPath":"https://…/doc-images/<org>/<doc>/image-….png"}
207
+
208
+ then put that `relPath` in a normal Markdown image: `![what it shows](<relPath>)`. Use
209
+ `inplan asset-upload <file> …` for a local plan promoted to the cloud (its doc id comes from
210
+ the status sidecar), and the `--remote <docId>` form for a doc you attached to by id. Both
211
+ upload as **you** — the signed-in session is the authorization, so there is no key to find
212
+ and nothing to configure beyond `inplan login`.
213
+
214
+ For a purely local plan, images live next to the file in `<docname>.assets/` and a relative
215
+ link resolves; nothing needs uploading.
216
+
217
+ Write the image reference in the same edit that adds the surrounding prose. Do not leave a
218
+ placeholder for the human to fill in later — attaching images is not a human-only step, and a
219
+ body full of bare filenames is the failure this section exists to prevent.
220
+
199
221
  ## Turn-taking & control — read this first
200
222
 
201
223
  This is **turn-based**. The turn belongs to exactly one party at a time:
@@ -268,6 +290,13 @@ the plan, then call `wait`.** Do not pass `--cursor` and do not hand-manage it.
268
290
  building what the document specifies (it's no longer a planning doc — act on it).
269
291
  - `window_closed` — they just closed the editor; **stop** and take no further action.
270
292
  - `crashed_or_killed` — the editor vanished with no close log; surface this to the human.
293
+ Only reported once the absence has persisted (a heartbeat that merely stalled — a
294
+ backgrounded tab, a network blip — is not a departure), and never in place of work you
295
+ were waiting for: if the human handed the turn back and *then* left, you get that
296
+ handoff (`your_turn` / `activity`) with **`editorGone: true`** alongside it. Treat that
297
+ flag as the closure: do the work the handoff describes, then **stop**. Do not call `wait`
298
+ again — the editor is already gone, so the next wait has nothing to see it leave and will
299
+ block rather than report it.
271
300
  - `superseded` — a newer `wait` took over this document (only one waiter runs at
272
301
  a time). This one stepped down; **do nothing** — the live waiter is in charge.
273
302
  - `navigated` — the human followed an in-window link to a **different document**;
@@ -302,13 +331,17 @@ the plan, then call `wait`.** Do not pass `--cursor` and do not hand-manage it.
302
331
  inplan wait <name>.plan.md
303
332
 
304
333
  `your_turn` and `activity` are **not** stop conditions — you always loop back
305
- and keep waiting. The **only** thing that ends the loop is `status: closed`.
334
+ and keep waiting. Two things end the loop: `status: closed`, or a handoff that
335
+ also carries `editorGone: true` (the human handed the turn back and then left —
336
+ finish that turn's work, then stop; see `crashed_or_killed` above for why a
337
+ further `wait` would block instead of reporting the closure).
306
338
 
307
339
  6. When you believe the plan is ready, signal it (the human still decides):
308
340
 
309
341
  inplan signal <name>.plan.md --done
310
342
 
311
- Then wait again. Stop only on `status: closed`.
343
+ Then wait again, and stop on the same two conditions as step 5: `status: closed`,
344
+ or a handoff carrying `editorGone: true`.
312
345
 
313
346
  ## Keeping the human informed
314
347