@proagentstore/cli 0.4.99 → 0.4.101

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.
@@ -21,6 +21,8 @@ export { defaultStatePath } from "./headless-state.js";
21
21
  * (refusing new records) would lose the turns that just happened rather than ancient ones.
22
22
  */
23
23
  const MAX_PENDING_USAGE = 200;
24
+ /** How many consumed-input ids a session reports (#1019). Re-sent on every snapshot, so bounded; the oldest fall off. */
25
+ export const MAX_CONSUMED_INPUTS = 50;
24
26
  /**
25
27
  * How many un-drained consequential acts a session holds (#294).
26
28
  *
@@ -92,6 +94,15 @@ export class HeadlessSession {
92
94
  stopped = false;
93
95
  /** How the last COMPLETED turn ended (#545). Null until one has. See {@link EngineTurnReport}. */
94
96
  turnReport = null;
97
+ /**
98
+ * Inputs written to the persistent process and not yet answered by a turn end, oldest first (#1019).
99
+ * `null` holds the place of an input sent without an id, so the ids after it stay aligned.
100
+ */
101
+ pendingInputs = [];
102
+ /** The id of the input the current one-shot turn was spawned for (#1019). */
103
+ turnInputId = null;
104
+ /** Ids of inputs a COMPLETED turn consumed, newest last and bounded (#1019). See {@link consumedInputs}. */
105
+ consumed = [];
95
106
  /**
96
107
  * The engine's own last output line of the turn in flight (#545).
97
108
  *
@@ -295,6 +306,27 @@ export class HeadlessSession {
295
306
  get lastTurn() {
296
307
  return this.turnReport;
297
308
  }
309
+ /**
310
+ * Ids of inputs a completed turn demonstrably consumed (#1019), newest last.
311
+ *
312
+ * The cloud used to mark an owner's message "processed" when ANY turn ended after it was sent —
313
+ * but a message queued behind a running turn arrives before that turn ends without being read
314
+ * by it. So consumption is correlated here, where the inputs are written: a one-shot turn
315
+ * consumed the input it was spawned for (unless we killed it); a persistent engine answers its
316
+ * inputs in order, so a turn end credits only the OLDEST outstanding one. If the engine folded
317
+ * two queued inputs into one turn, the second is credited one turn late — a delay, never a
318
+ * credit for something it had not read.
319
+ */
320
+ get consumedInputs() {
321
+ return this.consumed;
322
+ }
323
+ credit(id) {
324
+ if (!id)
325
+ return;
326
+ this.consumed.push(id);
327
+ if (this.consumed.length > MAX_CONSUMED_INPUTS)
328
+ this.consumed.shift();
329
+ }
298
330
  /** The engine process's pid while one is running — what per-session resource attribution reads (#924). */
299
331
  get pid() {
300
332
  return this.procAlive ? (this.proc?.pid ?? null) : null;
@@ -392,6 +424,8 @@ export class HeadlessSession {
392
424
  }
393
425
  if (this.procAlive)
394
426
  return;
427
+ // A new process has read none of what the old one was sent.
428
+ this.pendingInputs = [];
395
429
  const args = this.adapter.buildLaunchArgs(this.cmdArgs, this.claudeSessionId);
396
430
  const proc = spawn(this.cmdBin, args, {
397
431
  cwd: this.config.workDir,
@@ -493,8 +527,10 @@ export class HeadlessSession {
493
527
  // disambiguation rides in the text instead (#505).
494
528
  const msg = JSON.stringify({ type: "user", message: { role: "user", content: [{ type: "text", text: withSeed }] } });
495
529
  this.proc?.stdin?.write(`${msg}\n`);
530
+ this.pendingInputs.push(opts.inputId ?? null);
496
531
  }
497
532
  else {
533
+ this.turnInputId = opts.inputId ?? null;
498
534
  // Raw CLI: spawn THIS turn. See `oneShot` — there is no persistent process to
499
535
  // write to, because a non-interactive binary would never have read it.
500
536
  this.runOneShot(withSeed);
@@ -527,6 +563,7 @@ export class HeadlessSession {
527
563
  this.sawStructuredEvent = false;
528
564
  this.structuredOutputRejected = false;
529
565
  const resumedCodexThreadId = this.codexResumeThreadId;
566
+ const inputId = this.turnInputId;
530
567
  const turnArgs = resumedCodexThreadId
531
568
  ? buildCodexResumeArgs(this.cmdArgs, resumedCodexThreadId, text)
532
569
  : this.adapter.buildTurnArgs(this.cmdArgs, text);
@@ -626,6 +663,9 @@ export class HeadlessSession {
626
663
  // A signal means WE ended it (the wedge ceiling, an interrupt), which is the `killed`
627
664
  // verdict: evidence about this platform's timers, not about the engine's health.
628
665
  this.turnReport = turnReportFromExit(code, signal, this.turnLastLine, Date.now(), this.turnTail);
666
+ // A turn we killed did not finish reading its input (#1019).
667
+ if (this.turnReport.verdict !== "killed")
668
+ this.credit(inputId);
629
669
  this.run = "idle";
630
670
  this.proc = null;
631
671
  });
@@ -800,6 +840,7 @@ export class HeadlessSession {
800
840
  // own `is_error` — the same claim, in the words the engine states it in. Without
801
841
  // this the field would exist for three engines and silently not for the flagship.
802
842
  this.turnReport = turnReportFromResult(ev.isError, failure, Date.now(), this.turnTail);
843
+ this.credit(this.pendingInputs.shift() ?? null);
803
844
  // The same event that ends the turn also reports what the turn COST (#267). It was
804
845
  // parsed and thrown away, which is why Engine spend was absent from the ledger.
805
846
  // An errored turn still burned tokens, so this is recorded regardless of is_error.
@@ -240,6 +240,7 @@ export class CodingRuntime {
240
240
  // last turn end" is exactly the question asked about a session that just stopped, and
241
241
  // the omitted-when-null shape keeps "not measured" distinguishable from a verdict.
242
242
  ...(session.lastTurn ? { lastTurn: session.lastTurn } : {}),
243
+ ...(session.consumedInputs.length ? { consumedInputs: [...session.consumedInputs] } : {}),
243
244
  ...(opts.drainUsage ? { usage: session.takeUsage(), acts: session.takeActs() } : {}),
244
245
  };
245
246
  }
@@ -250,7 +251,11 @@ export class CodingRuntime {
250
251
  case "message":
251
252
  // Narrowed rather than trusted: this runner is a published package any caller can
252
253
  // POST to, and an unrecognised author must read as "unstated", not become a label.
253
- session.input(action.text, { author: asTurnAuthor(action.author), replay: typeof action.replay === "string" ? action.replay : undefined });
254
+ session.input(action.text, {
255
+ author: asTurnAuthor(action.author),
256
+ replay: typeof action.replay === "string" ? action.replay : undefined,
257
+ inputId: typeof action.inputId === "string" && action.inputId.length <= 128 ? action.inputId : undefined,
258
+ });
254
259
  break;
255
260
  case "keys": {
256
261
  // A snapshot is no longer the whole answer (#448). `key()` records the attempt and
package/dist/index.js CHANGED
@@ -1730,11 +1730,18 @@ function mayAutomaticallyRestart(input) {
1730
1730
  }
1731
1731
 
1732
1732
  // src/commands/runner/auto-update-controller.ts
1733
+ var MAX_OBSERVATIONS = 5;
1734
+ var IDLE_RETRY_MS = 15e3;
1735
+ function blockerClassFor(waitingFor) {
1736
+ if (waitingFor.includes("runner-work-observation-unavailable")) return "observation_failure";
1737
+ return waitingFor.length ? "active_sessions" : "unknown";
1738
+ }
1733
1739
  var AutomaticUpdateController = class {
1734
1740
  constructor(deps) {
1735
1741
  this.deps = deps;
1736
1742
  this.setTimer = deps.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
1737
1743
  this.clearTimer = deps.clearTimer ?? ((timer) => clearTimeout(timer));
1744
+ this.now = deps.now ?? Date.now;
1738
1745
  }
1739
1746
  deps;
1740
1747
  timer = null;
@@ -1742,8 +1749,18 @@ var AutomaticUpdateController = class {
1742
1749
  waiting = false;
1743
1750
  installing = false;
1744
1751
  failures = 0;
1752
+ checkAt = null;
1753
+ decisionAt = null;
1754
+ nextRetryDueAt = null;
1755
+ blockerClass = null;
1756
+ observations = [];
1757
+ now;
1745
1758
  setTimer;
1746
1759
  clearTimer;
1760
+ /** The controller's own record, safe to report: times, a normalized class, and observation outcomes. */
1761
+ diagnostics() {
1762
+ return { checkAt: this.checkAt, decisionAt: this.decisionAt, nextRetryDueAt: this.nextRetryDueAt, blockerClass: this.blockerClass, observations: [...this.observations] };
1763
+ }
1747
1764
  /** Called only for a true policy transition. `keep` deliberately leaves a due heartbeat timer alone. */
1748
1765
  onPolicy(action) {
1749
1766
  if (action === "cancel") return this.cancel();
@@ -1756,10 +1773,10 @@ var AutomaticUpdateController = class {
1756
1773
  this.checking = true;
1757
1774
  try {
1758
1775
  if (!await this.deps.refreshPolicy() || !this.enabled()) {
1759
- this.deps.status("offline", { reason: "The owner policy could not be refreshed; automatic update is deferred." });
1776
+ this.offline();
1760
1777
  return;
1761
1778
  }
1762
- await this.decide(false);
1779
+ await this.decide();
1763
1780
  } catch (error) {
1764
1781
  this.fail(error);
1765
1782
  } finally {
@@ -1779,23 +1796,40 @@ var AutomaticUpdateController = class {
1779
1796
  const delay = initial ? Math.round(5e3 + (this.deps.random ?? Math.random)() * 25e3) : nextAutoUpdateDelayMs(this.failures, this.deps.random);
1780
1797
  this.timer = this.setTimer(() => {
1781
1798
  this.timer = null;
1799
+ this.nextRetryDueAt = null;
1782
1800
  void this.runNow();
1783
1801
  }, delay);
1784
1802
  this.timer.unref?.();
1803
+ this.nextRetryDueAt = this.now() + delay;
1785
1804
  }
1786
1805
  cancel() {
1787
1806
  if (this.timer) this.clearTimer(this.timer);
1788
1807
  this.timer = null;
1808
+ this.nextRetryDueAt = null;
1809
+ }
1810
+ /**
1811
+ * The owner policy could not be re-read, so nothing installs (fail closed) — but the controller keeps
1812
+ * a timer (#1020). It used to report `offline` and stop, leaving an enabled runner with no callback
1813
+ * until the next policy transition. `schedule` itself refuses once the policy is disabled.
1814
+ */
1815
+ offline() {
1816
+ this.failures++;
1817
+ this.deps.status("offline", { reason: "The owner policy could not be refreshed; automatic update is deferred." });
1818
+ this.schedule();
1789
1819
  }
1790
1820
  fail(error) {
1791
1821
  this.failures++;
1792
1822
  this.deps.status("failure", { reason: error instanceof Error ? error.message : String(error) });
1793
1823
  this.schedule();
1794
1824
  }
1795
- async decide(deferred) {
1825
+ async decide() {
1796
1826
  const facts = await this.deps.facts();
1827
+ this.checkAt = this.now();
1828
+ if (facts.observations?.length) this.observations = [...this.observations, ...facts.observations].slice(-MAX_OBSERVATIONS);
1797
1829
  if (!this.enabled()) return;
1798
1830
  const plan = this.deps.plan(facts);
1831
+ this.decisionAt = this.now();
1832
+ this.blockerClass = plan.action === "wait" ? blockerClassFor(plan.waitingFor) : null;
1799
1833
  if (plan.action === "up-to-date") {
1800
1834
  this.failures = 0;
1801
1835
  this.deps.status("verified-success", { latestVersion: facts.latest ?? void 0, reason: void 0 });
@@ -1814,28 +1848,34 @@ var AutomaticUpdateController = class {
1814
1848
  }
1815
1849
  this.deps.status("running", { latestVersion: plan.latest, reason: void 0 });
1816
1850
  const restarted = await this.install(plan, true);
1817
- if (restarted) this.deps.status("restarting", { latestVersion: plan.latest, reason: void 0 });
1818
- else if (!deferred) this.defer(plan.latest);
1851
+ if (restarted) {
1852
+ this.deps.status("restarting", { latestVersion: plan.latest, reason: void 0 });
1853
+ return;
1854
+ }
1855
+ this.blockerClass = "idle_wait";
1856
+ this.defer(plan.latest);
1819
1857
  }
1820
1858
  defer(latest) {
1821
1859
  if (this.waiting) return;
1822
1860
  this.waiting = true;
1823
1861
  this.timer = this.setTimer(() => {
1824
1862
  this.timer = null;
1863
+ this.nextRetryDueAt = null;
1825
1864
  void (async () => {
1826
1865
  this.waiting = false;
1827
1866
  try {
1828
1867
  if (!await this.deps.refreshPolicy() || !this.enabled()) {
1829
- this.deps.status("offline", { reason: "The owner policy could not be refreshed; automatic update is deferred." });
1868
+ this.offline();
1830
1869
  return;
1831
1870
  }
1832
- await this.decide(true);
1871
+ await this.decide();
1833
1872
  } catch (error) {
1834
1873
  this.fail(error);
1835
1874
  }
1836
1875
  })();
1837
- }, 15e3);
1876
+ }, IDLE_RETRY_MS);
1838
1877
  this.timer.unref?.();
1878
+ this.nextRetryDueAt = this.now() + IDLE_RETRY_MS;
1839
1879
  this.deps.status("waiting-for-idle", latest ? { latestVersion: latest } : void 0);
1840
1880
  }
1841
1881
  async install(plan, automatic) {
@@ -1914,6 +1954,7 @@ async function connectViaRelay(instanceIds, localUrl, runnerToken, opts, force =
1914
1954
  let autoUpdatePolicyAuthoritative = false;
1915
1955
  let refreshingAutomaticPolicy = false;
1916
1956
  let scheduleAutomaticUpdate = () => void 0;
1957
+ let autoUpdateDiagnostics = () => ({});
1917
1958
  const saveAutoUpdateStatus = (status, extra = {}) => {
1918
1959
  autoUpdatePolicy = {
1919
1960
  ...autoUpdatePolicy,
@@ -1959,7 +2000,8 @@ async function connectViaRelay(instanceIds, localUrl, runnerToken, opts, force =
1959
2000
  autoUpdateStatus: {
1960
2001
  status: autoUpdateStatusWire(autoUpdatePolicy.status),
1961
2002
  latestVersion: autoUpdatePolicy.latestVersion,
1962
- error: autoUpdatePolicy.reason
2003
+ error: autoUpdatePolicy.reason,
2004
+ ...autoUpdateDiagnostics()
1963
2005
  }
1964
2006
  });
1965
2007
  acceptAutoUpdatePolicy(result);
@@ -2006,7 +2048,14 @@ async function connectViaRelay(instanceIds, localUrl, runnerToken, opts, force =
2006
2048
  requestRunner("GET", "/health", { url: localUrl, token: runnerToken, instanceId: instanceIds[0] })
2007
2049
  ]);
2008
2050
  const busy = sessionsResult.status === "fulfilled" && healthResult.status === "fulfilled" ? observedRunnerWork({ sessions: sessionsResult.value.sessions, work: healthResult.value.work }) : ["runner-work-observation-unavailable"];
2051
+ const sampledAt = Date.now();
2052
+ const observations = [
2053
+ // An answer is a success only when it has the shape the guard reads; malformed is a failed look.
2054
+ { source: "sessions", success: sessionsResult.status === "fulfilled" && Array.isArray(sessionsResult.value.sessions), sampledAt },
2055
+ { source: "health", success: healthResult.status === "fulfilled" && !!healthResult.value.work && typeof healthResult.value.work === "object", sampledAt }
2056
+ ];
2009
2057
  return {
2058
+ observations,
2010
2059
  current: CLI_VERSION,
2011
2060
  latest: await latestPublishedVersion(),
2012
2061
  fromSource: runsFromSource(),
@@ -2196,6 +2245,7 @@ async function connectViaRelay(instanceIds, localUrl, runnerToken, opts, force =
2196
2245
  },
2197
2246
  status: saveAutoUpdateStatus
2198
2247
  });
2248
+ autoUpdateDiagnostics = () => automaticUpdateController.diagnostics();
2199
2249
  scheduleAutomaticUpdate = (initial = false, cancel = false) => automaticUpdateController.onPolicy(cancel ? "cancel" : initial ? "start" : "keep");
2200
2250
  if (autoUpdatePolicyAuthoritative && autoUpdatePolicy.autoUpdate) scheduleAutomaticUpdate(true);
2201
2251
  const answerUpdate = async (body) => {
@@ -2331,7 +2381,8 @@ async function connectViaRelay(instanceIds, localUrl, runnerToken, opts, force =
2331
2381
  autoUpdateStatus: {
2332
2382
  status: autoUpdateStatusWire(autoUpdatePolicy.status),
2333
2383
  latestVersion: autoUpdatePolicy.latestVersion,
2334
- error: autoUpdatePolicy.reason
2384
+ error: autoUpdatePolicy.reason,
2385
+ ...autoUpdateDiagnostics()
2335
2386
  }
2336
2387
  });
2337
2388
  acceptAutoUpdatePolicy(response);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@proagentstore/cli",
3
- "version": "0.4.99",
3
+ "version": "0.4.101",
4
4
  "description": "CLI for creating, publishing, and running ProAgentStore agents",
5
5
  "license": "MIT",
6
6
  "type": "module",