@nodii/dev 0.6.147 → 0.6.148

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/dist/cli.js CHANGED
@@ -35,6 +35,7 @@ import { installManagedLatest, managedStatus } from "./managed-version.js";
35
35
  import { dispatchManagedClaudeHook, dispatchManagedHook } from "./managed-hooks.js";
36
36
  import { governorCommand, laneClose } from "./governor.js";
37
37
  import { freezeCommand } from "./freeze.js";
38
+ import { laneReadCache } from "./read-cache.js";
38
39
  import {
39
40
  figmaChangeSetShow,
40
41
  figmaChangeSetList,
@@ -838,6 +839,14 @@ export async function figmaFileAdd(value, flags, { request = devRequest } = {})
838
839
  // blocks the lane: a blocked lane needs them to unblock itself (AGENT-HARNESS-14).
839
840
  const readsHelp = (argv) => argv[0] === "help" || argv.some((token) => ["--help", "-h"].includes(token)) || (argv.length === 1 && ["--version", "-v"].includes(argv[0]));
840
841
 
842
+ // cli-134: the managed hooks run this backstop on every tool call (one lane read
843
+ // both routes about once a second), yet a hook cannot enforce it: a hook exits 0
844
+ // on anything but a SAFETY_ or Figma denial, and its banner is never claimed. So
845
+ // a hook reuses an answer for 15 seconds. Every other command reads Dev fresh,
846
+ // so it is blocked by an unacknowledged amendment (CTRL-CLI-34) and shows a
847
+ // new Result (MW5-16) on its next call, exactly as before.
848
+ export const backstopCache = (argv) => (argv[0] === "hook" ? laneReadCache() : null);
849
+
841
850
  export async function main(argv = process.argv.slice(2)) {
842
851
  // Ahead of every check that reaches Dev: a session the lane spawned gets
843
852
  // nothing from these hooks. The safety hooks still run.
@@ -851,8 +860,9 @@ export async function main(argv = process.argv.slice(2)) {
851
860
  // The heartbeat hook fires on every tool call, so these checks would call Dev each
852
861
  // time past its rate limit, and a failed check would silently stop the heartbeat.
853
862
  if (argv[0] !== "__run-supervisor" && !readsHelp(argv) && !(argv[0] === "hook" && (argv[1]?.startsWith("nudge-") || argv[1] === "surface-gen-pre" || argv[1] === "lane-heartbeat"))) {
854
- await amendmentGuard(argv);
855
- await showWaitingResults({ acknowledge: argv[0] !== "hook" });
863
+ const cache = backstopCache(argv);
864
+ await amendmentGuard(argv, { cache });
865
+ await showWaitingResults({ acknowledge: argv[0] !== "hook", cache });
856
866
  }
857
867
  if (argv.length === 1 && ["--version", "-v"].includes(argv[0]))
858
868
  return console.log(VERSION);
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, platform } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.147";
7
+ export const VERSION = "0.6.148";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
@@ -135,7 +135,56 @@ const withSignal = (promise, signal) => {
135
135
  });
136
136
  };
137
137
 
138
+ // cli-134: a 429 with Retry-After is shown and waited out once, then the call
139
+ // is sent once more; a second 429, a missing Retry-After or a wait longer than
140
+ // RETRY_AFTER_MAX_MS is surfaced with Dev's message. Never a loop.
141
+ export const RETRY_AFTER_MAX_MS = 20_000;
142
+ const defaultRetrySleep = (ms, signal) => new Promise((resolvePromise, rejectPromise) => {
143
+ const timer = setTimeout(resolvePromise, ms);
144
+ signal?.addEventListener("abort", () => { clearTimeout(timer); rejectPromise(signal.reason ?? new Error("aborted")); }, { once: true });
145
+ });
146
+ let retrySleep = defaultRetrySleep;
147
+ /** Tests replace the Retry-After wait; `null` restores the real one. */
148
+ export function setRetrySleep(fn) {
149
+ retrySleep = fn ?? defaultRetrySleep;
150
+ }
151
+
152
+ /** Retry-After in milliseconds (delta-seconds or an HTTP date), or null. */
153
+ export function retryAfterMs(value, now = Date.now()) {
154
+ const text = String(value ?? "").trim();
155
+ if (!text) return null;
156
+ if (/^\d+$/.test(text)) return Number(text) * 1000;
157
+ const at = Date.parse(text);
158
+ return Number.isFinite(at) ? Math.max(0, at - now) : null;
159
+ }
160
+
161
+ const refusalMessage = (raw) => {
162
+ try {
163
+ return JSON.parse(raw)?.message ?? null;
164
+ } catch {
165
+ return null;
166
+ }
167
+ };
168
+
138
169
  async function devFetchOnce(method, path, bodyText, contentType, accept, extra = {}, signal) {
170
+ const first = await devFetchSend(method, path, bodyText, contentType, accept, extra, signal);
171
+ if (first.response.status !== 429) return first;
172
+ const waitMs = retryAfterMs(first.response.headers?.get?.("retry-after"));
173
+ if (waitMs === null || waitMs > RETRY_AFTER_MAX_MS) return first;
174
+ const seconds = Math.ceil(waitMs / 1000);
175
+ try {
176
+ process.stderr.write(`Dev is rate limiting ${method} ${path}: ${refusalMessage(first.raw) ?? "HTTP 429"} Waiting ${seconds} s as Dev asks, then sending it once more.\n`);
177
+ } catch {}
178
+ try {
179
+ await retrySleep(waitMs, signal);
180
+ } catch (error) {
181
+ if (signal?.aborted) throw new CliError("DEV_TIMEOUT", `Dev request timed out: ${method} ${path}`, 1);
182
+ throw error;
183
+ }
184
+ return devFetchSend(method, path, bodyText, contentType, accept, extra, signal);
185
+ }
186
+
187
+ async function devFetchSend(method, path, bodyText, contentType, accept, extra = {}, signal) {
139
188
  const wait = async (promise) => {
140
189
  try {
141
190
  return await withSignal(promise, signal);
@@ -301,13 +350,16 @@ export async function devExchange(method, path, bodyText, { contentType = "appli
301
350
  }
302
351
  // Dev answers pending work as 202 with its error envelope (FIGMA_PLACEMENT_PENDING):
303
352
  // a 2xx alone doesn't mean the change was made.
304
- if (!response.ok || payload.error === true)
353
+ if (!response.ok || payload.error === true) {
354
+ const waitMs = response.status === 429 ? retryAfterMs(response.headers?.get?.("retry-after")) : null;
355
+ const after = waitMs === null ? "" : ` Dev asks to wait ${Math.ceil(waitMs / 1000)} s before trying again.`;
305
356
  throw new CliError(
306
357
  payload.code ?? `HTTP_${response.status}`,
307
- payload.message ?? `Dev returned HTTP ${response.status}`,
358
+ `${payload.message ?? `Dev returned HTTP ${response.status}`}${after}`,
308
359
  1,
309
360
  payload.details,
310
361
  );
362
+ }
311
363
  return { status: response.status, payload };
312
364
  }
313
365
 
package/dist/freeze.js CHANGED
@@ -3,6 +3,7 @@ import { readFile, realpath } from "node:fs/promises";
3
3
  import { resolve } from "node:path";
4
4
  import { promisify } from "node:util";
5
5
  import { CliError, devRequest, encode, query, readConfig, requireFlag } from "./core.js";
6
+ import { cachedGet, cachingRequest } from "./read-cache.js";
6
7
 
7
8
  const execFileAsync = promisify(execFile);
8
9
  const TERMINAL = new Set(["on_dev", "stopped", "non_issue"]);
@@ -262,11 +263,13 @@ async function acknowledge(ref, data, request) {
262
263
  */
263
264
  export async function regroundCurrentLane(
264
265
  { cwd = process.cwd(), force = false, write = (text) => process.stderr.write(text) } = {},
265
- { request = devRequest, config = readConfig } = {},
266
+ { request = devRequest, config = readConfig, cache = null } = {},
266
267
  ) {
267
- const lane = await currentLane({ cwd }, { request, config });
268
+ // cli-134: the entry point passes the lane read cache, so a script calling
269
+ // nodii-dev twice a second finds its lane and Freeze at most once per 15 s.
270
+ const lane = await currentLane({ cwd }, { request: cachingRequest(cache, request), config });
268
271
  if (!lane) return { shown: false, reason: "no active lane" };
269
- return regroundLane(lane, { force, write }, { request });
272
+ return regroundLane(lane, { force, write }, { request, cache });
270
273
  }
271
274
 
272
275
  /**
@@ -276,12 +279,12 @@ export async function regroundCurrentLane(
276
279
  export async function regroundLane(
277
280
  lane,
278
281
  { force = false, write = (text) => process.stderr.write(text) } = {},
279
- { request = devRequest } = {},
282
+ { request = devRequest, cache = null } = {},
280
283
  ) {
281
- const response = await request(
282
- "GET",
283
- `/api/v1/lanes/${encode(lane.key)}/freeze`,
284
- );
284
+ const path = `/api/v1/lanes/${encode(lane.key)}/freeze`;
285
+ // A Freeze that asks to be acknowledged is never cached: it is shown and
286
+ // acknowledged from Dev's own answer, and only then remembered as acknowledged.
287
+ const response = await cachedGet(force ? null : cache, request, path, (answer) => !answer?.data?.requiresAcknowledgement);
285
288
  const data = response.data;
286
289
  if (!data?.freeze || !data.markdown)
287
290
  return { shown: false, reason: "Freeze not initialized", lane };
@@ -289,7 +292,9 @@ export async function regroundLane(
289
292
  return { shown: false, reason: "already acknowledged", lane, data };
290
293
  write(`Freeze re-grounding for ${lane.key} (v${data.version}):\n${data.markdown}\n`);
291
294
  await acknowledge(lane.key, data, request);
292
- return { shown: true, lane, data: { ...data, acknowledged: true, requiresAcknowledgement: false } };
295
+ const acknowledged = { ...data, acknowledged: true, requiresAcknowledgement: false };
296
+ await cache?.set(path, { ...response, data: acknowledged });
297
+ return { shown: true, lane, data: acknowledged };
293
298
  }
294
299
 
295
300
  async function valueFromFile(flags, read) {
package/dist/nodii-dev.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { fail, main } from "./cli.js";
3
3
  import { regroundCurrentLane, shouldReground } from "./freeze.js";
4
4
  import { isHookDenial } from "./hooks.js";
5
+ import { laneReadCache } from "./read-cache.js";
5
6
  import { drainStdout, routeStdout } from "./stdout.js";
6
7
 
7
8
  routeStdout();
@@ -21,7 +22,8 @@ async function run() {
21
22
  }
22
23
  // AGENT-HARNESS-19: this is the executable boundary, so every ordinary CLI
23
24
  // invocation re-grounds without adding hidden requests to library callers.
24
- if (shouldReground(argv)) await regroundCurrentLane();
25
+ // cli-134: through the lane read cache, at most once per 15 seconds.
26
+ if (shouldReground(argv)) await regroundCurrentLane({}, { cache: laneReadCache() });
25
27
  await main(argv);
26
28
  }
27
29
 
@@ -0,0 +1,75 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { configPath } from "./core.js";
5
+
6
+ // cli-134: every nodii-dev invocation from a lane (the managed hooks run on every
7
+ // tool call) read the lane's amendments, the run's results and the lane's Freeze.
8
+ // One lane made 1,322 requests in 10 minutes. These reads now go through a small
9
+ // on-disk cache: a repeat within 15 seconds reuses the last answer, so an approved
10
+ // amendment or a new Freeze still reaches the lane within about 15 seconds.
11
+ // Only "nothing to do" answers are kept (see each caller): an answer that blocks
12
+ // the lane or asks for an acknowledgement is always read fresh.
13
+ export const READ_CACHE_TTL_MS = 15_000;
14
+ const PRUNE_AFTER_MS = 60 * 60_000;
15
+
16
+ const defaultDir = () => join(dirname(configPath()), "read-cache");
17
+
18
+ /**
19
+ * A best-effort cache keyed by Dev path (and this agent's config). Every file
20
+ * error is a miss: the cache never fails a command.
21
+ */
22
+ export function laneReadCache({ dir = defaultDir(), ttlMs = READ_CACHE_TTL_MS, now = Date.now } = {}) {
23
+ const scope = configPath();
24
+ const file = (path) => join(dir, `${createHash("sha256").update(`${scope}\n${path}`).digest("hex").slice(0, 32)}.json`);
25
+ return {
26
+ async get(path) {
27
+ try {
28
+ const entry = JSON.parse(await readFile(file(path), "utf8"));
29
+ const age = now() - entry.at;
30
+ if (entry.path !== path || !(age >= 0 && age < ttlMs)) return undefined;
31
+ return entry.value;
32
+ } catch {
33
+ return undefined;
34
+ }
35
+ },
36
+ async set(path, value) {
37
+ try {
38
+ await mkdir(dir, { recursive: true, mode: 0o700 });
39
+ const target = file(path);
40
+ const temporary = `${target}.${process.pid}.${randomUUID()}`;
41
+ await writeFile(temporary, JSON.stringify({ path, at: now(), value }), { mode: 0o600 });
42
+ await rename(temporary, target);
43
+ if (Math.random() < 0.05) await prune(dir, now());
44
+ } catch {}
45
+ },
46
+ async drop(path) {
47
+ try {
48
+ await rm(file(path), { force: true });
49
+ } catch {}
50
+ },
51
+ };
52
+ }
53
+
54
+ async function prune(dir, at) {
55
+ for (const name of await readdir(dir)) {
56
+ try {
57
+ const path = join(dir, name);
58
+ if (at - (await stat(path)).mtimeMs > PRUNE_AFTER_MS) await rm(path, { force: true });
59
+ } catch {}
60
+ }
61
+ }
62
+
63
+ /** A GET through the cache: a fresh entry answers; else Dev does, and `keep(answer)` decides whether to store it. */
64
+ export async function cachedGet(cache, request, path, keep = () => true) {
65
+ if (!cache) return request("GET", path);
66
+ const hit = await cache.get(path);
67
+ if (hit !== undefined) return hit;
68
+ const answer = await request("GET", path);
69
+ if (keep(answer)) await cache.set(path, answer);
70
+ return answer;
71
+ }
72
+
73
+ /** A request function whose GETs go through the cache; every other method goes to Dev. */
74
+ export const cachingRequest = (cache, request) =>
75
+ cache ? (method, path, body, options) => (method === "GET" && body === undefined ? cachedGet(cache, request, path) : request(method, path, body, options)) : request;
package/dist/runs.js CHANGED
@@ -4,6 +4,7 @@ import { readFile } from "node:fs/promises";
4
4
  import { basename } from "node:path";
5
5
  import { CliError, devRequest, encode } from "./core.js";
6
6
  import { heavySlotArgv, needsSlot } from "./heavy.js";
7
+ import { cachedGet } from "./read-cache.js";
7
8
 
8
9
  export const RUN_ID_ENV = "NODII_DEV_RUN_ID";
9
10
  const DEFAULT_HEARTBEAT_MS = 60_000;
@@ -80,12 +81,17 @@ export async function showWaitingResults({
80
81
  request = devRequest,
81
82
  write = (value) => process.stderr.write(value),
82
83
  acknowledge = true,
84
+ cache = null,
83
85
  } = {}) {
84
86
  const waiterRunId = currentRunId(runId);
85
87
  if (!waiterRunId) return [];
86
- const payload = await request(
87
- "GET",
88
+ // cli-134: only "no results waiting" is cached; a waiting result is always
89
+ // read fresh, so it is shown and acknowledged from Dev's own answer.
90
+ const payload = await cachedGet(
91
+ cache,
92
+ request,
88
93
  `/api/v1/runs/${encode(waiterRunId)}/results`,
94
+ (answer) => Array.isArray(answer?.data) && !answer.data.length,
89
95
  );
90
96
  const results = payload.data ?? [];
91
97
  if (!results.length) return [];
package/dist/starting.js CHANGED
@@ -10,6 +10,7 @@ import { laneCommand, nextCommand } from "./lanes.js";
10
10
  import { assertGovernorOpen, readGovernor } from "./governor.js";
11
11
  import { laneConfigName } from "./lane-env.js";
12
12
  import { hostBootedAt } from "./host.js";
13
+ import { cachedGet } from "./read-cache.js";
13
14
  import { accountFlags, listAccounts, profilePath, registerAccount, reportUsage, usageLine } from "./accounts.js";
14
15
 
15
16
  const execFile = promisify(execFileCallback);
@@ -951,12 +952,14 @@ export async function currentMarker(run = execFile, load = loadJson, env = proce
951
952
  return { ...marker, runId };
952
953
  }
953
954
 
954
- export async function amendmentGuard(argv, { request = devRequest, marker = currentMarker } = {}) {
955
+ export async function amendmentGuard(argv, { request = devRequest, marker = currentMarker, cache = null } = {}) {
955
956
  const lane = await marker();
956
957
  if (!lane) return null;
957
958
  const [command, action] = argv.filter((token) => !token.startsWith("--"));
958
959
  if ((command === "lane" && action === "gather" && argv.includes("--delta")) || (command === "lane" && action === "amend")) return lane;
959
- const pending = await request("GET", `/api/v1/lanes/${encode(lane.laneKey)}/amendments${query({ runId: lane.runId })}`);
960
+ // cli-134: only "nothing pending" is cached, so a pending amendment always
961
+ // blocks from Dev's own answer and its acknowledgement is seen at once.
962
+ const pending = await cachedGet(cache, request, `/api/v1/lanes/${encode(lane.laneKey)}/amendments${query({ runId: lane.runId })}`, (answer) => Array.isArray(answer?.data) && !answer.data.length);
960
963
  if (!pending.data.length) return lane;
961
964
  const detail = pending.data.map((item) => `v${item.version} ${item.reason}: ${JSON.stringify(item.change)}`).join("\n");
962
965
  const next = `nodii-dev lane gather ${lane.laneKey} --delta`;
package/dist/surface.js CHANGED
@@ -1451,7 +1451,8 @@ function liftFieldControls(code, node, ctx, lift, scope) {
1451
1451
  }
1452
1452
 
1453
1453
  /** A metric card's values that are Figma's sample, never copy (NODII-DEV-CLI-84). */
1454
- const METRIC_VALUES = ["value", "caption", "changeAmount", "period"];
1454
+ // statusTone and tone are the KPI's state ("Unresolved" warning or danger), never the sample's dot (hub-477).
1455
+ const METRIC_VALUES = ["value", "caption", "changeAmount", "period", "statusTone", "tone"];
1455
1456
 
1456
1457
  /**
1457
1458
  * Each opening tag of `names` (a regex alternation) in `code`, its attributes
@@ -2286,6 +2287,11 @@ function tabStrip(run, ctx) {
2286
2287
  const triggers = tabs.map((t, i) => {
2287
2288
  let trigger = t.trigger.replace(/(<TabsTrigger\b[\s\S]*?)\bvalue="tab"/, `$1value="${values[i]}"`);
2288
2289
  if (counted[i]) trigger = trigger.replace(counted[i], `{${mark(ctx, strip, joinName(camelName(values[i]), "tabLabel"), null)}}`);
2290
+ // A tab's count badge counts the viewer's action items: the page's, named by its tab, never
2291
+ // Figma's sample (`actionableCount={5}`) or one count every tab shares; its floor ("99+") too (hub-477).
2292
+ const own = (prop) => `${prop}={${mark(ctx, strip, joinName(camelName(values[i]), prop), null)}}`;
2293
+ trigger = trigger.replace(/(<TabsTrigger\b[\s\S]*?)\bactionableCount=\{(?:\d+|(?:__s\d+_)?actionableCount)\}/, (_, head) => `${head}${own("actionableCount")}`);
2294
+ trigger = trigger.replace(/(<TabsTrigger\b[\s\S]*?)\bcountIsFloor(?=\s|>)/, (_, head) => `${head}${own("countIsFloor")}`);
2289
2295
  return shownWhen(`(${visible}?.includes(${JSON.stringify(values[i])}) ?? true)`, indent(trigger, 3), 2);
2290
2296
  });
2291
2297
  return [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.147",
3
+ "version": "0.6.148",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {