@usepowerplant/cli 0.4.27 → 0.4.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c205f968-8b28-5dc5-9420-5b3fae8d2c6f")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d3cdc2c4-688f-5244-bc1d-b1fd4151981c")}catch(e){}}();
3
3
  import { createRequire as __cliCreateRequire } from 'node:module';
4
4
  const require = __cliCreateRequire(import.meta.url);
5
5
  var __create = Object.create;
@@ -20448,19 +20448,19 @@ var require_round_robin_pool = __commonJS({
20448
20448
  this[kAddClient](dispatcher);
20449
20449
  return dispatcher;
20450
20450
  }
20451
- let checked = 0;
20452
- while (checked < clientsLength) {
20451
+ let checked2 = 0;
20452
+ while (checked2 < clientsLength) {
20453
20453
  this[kIndex] = (this[kIndex] + 1) % clientsLength;
20454
20454
  const client = this[kClients][this[kIndex]];
20455
20455
  if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) {
20456
20456
  this[kRemoveClient](client);
20457
- checked++;
20457
+ checked2++;
20458
20458
  continue;
20459
20459
  }
20460
20460
  if (!client[kNeedDrain]) {
20461
20461
  return client;
20462
20462
  }
20463
- checked++;
20463
+ checked2++;
20464
20464
  }
20465
20465
  if (!this[kConnections] || clientsLength < this[kConnections]) {
20466
20466
  const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
@@ -57797,6 +57797,13 @@ function scrubBreadcrumb(breadcrumb) {
57797
57797
  return breadcrumb;
57798
57798
  }
57799
57799
 
57800
+ // ../core/src/htmlErrorPage.ts
57801
+ var HTML_PAGE_TITLE_MAX_CHARS = 80;
57802
+ function htmlPageTitle(page) {
57803
+ const title = /<title>([^<]*)<\/title>/i.exec(page)?.[1]?.replace(/\s+/g, " ").trim();
57804
+ return title ? title.slice(0, HTML_PAGE_TITLE_MAX_CHARS).trimEnd() : null;
57805
+ }
57806
+
57800
57807
  // ../core/src/freshness.ts
57801
57808
  function describeDataAge(generatedAt, now) {
57802
57809
  const ageMs = now.getTime() - generatedAt.getTime();
@@ -84853,8 +84860,169 @@ function _init2(options = {}, getDefaultIntegrationsImpl) {
84853
84860
  return client;
84854
84861
  }
84855
84862
 
84863
+ // ../../apps/syncservice/src/http.ts
84864
+ import tls2 from "node:tls";
84865
+ var import_undici = __toESM(require_undici(), 1);
84866
+ var CLI_VERSION_HEADER = "x-powerplant-cli-version";
84867
+ var cliVersion = true ? "0.4.28" : "0.0.0-checkout";
84868
+ function cliVersionHeaders() {
84869
+ return { [CLI_VERSION_HEADER]: cliVersion, "user-agent": `powerplant-cli/${cliVersion}` };
84870
+ }
84871
+ function withVersionHeader(init3) {
84872
+ const headers = new Headers(init3?.headers);
84873
+ for (const [name, value] of Object.entries(cliVersionHeaders())) headers.set(name, value);
84874
+ return { ...init3, headers };
84875
+ }
84876
+ function installHttpTransport(env, certificates = tls2) {
84877
+ trustSystemCertificates(certificates);
84878
+ const { ignored, ...settings } = proxySettings(env);
84879
+ (0, import_undici.setGlobalDispatcher)(new import_undici.EnvHttpProxyAgent({ allowH2: false, ...settings }));
84880
+ if (ignored.length === 0) return null;
84881
+ return `Powerplant ignores ${ignored.join(" and ")}. It can use only an address like http://user:password@proxy.example.com:8080. Write a % in a password as %25.`;
84882
+ }
84883
+ function trustSystemCertificates(store) {
84884
+ const { getCACertificates, setDefaultCACertificates } = store;
84885
+ if (getCACertificates === void 0 || setDefaultCACertificates === void 0) return;
84886
+ const defaults = getCACertificates("default");
84887
+ const current = new Set(defaults);
84888
+ if (!getCACertificates("bundled").every((root) => current.has(root))) return;
84889
+ setDefaultCACertificates([...defaults, ...getCACertificates("system")]);
84890
+ }
84891
+ function proxySettings(env) {
84892
+ const ignored = [];
84893
+ const address = (name) => {
84894
+ const found = environmentVariable(env, name);
84895
+ if (found === void 0) return "";
84896
+ const value = /^[a-z][a-z\d+.-]*:\/\//i.test(found.value) ? found.value : `http://${found.value}`;
84897
+ const url2 = URL.canParse(value) ? new URL(value) : null;
84898
+ const usable = url2 !== null && ["http:", "https:"].includes(url2.protocol) && url2.username === "" === (url2.password === "") && undiciAccepts(value);
84899
+ if (usable) return value;
84900
+ ignored.push(found.name);
84901
+ return "";
84902
+ };
84903
+ return {
84904
+ httpProxy: address("http_proxy"),
84905
+ httpsProxy: address("https_proxy"),
84906
+ noProxy: environmentVariable(env, "no_proxy")?.value ?? "",
84907
+ ignored
84908
+ };
84909
+ }
84910
+ function undiciAccepts(address) {
84911
+ try {
84912
+ void new import_undici.ProxyAgent(address).close();
84913
+ return true;
84914
+ } catch {
84915
+ return false;
84916
+ }
84917
+ }
84918
+ function environmentVariable(env, name) {
84919
+ const listed = Object.keys(env);
84920
+ for (const key of [name, name.toUpperCase()]) {
84921
+ const value = env[key]?.trim();
84922
+ if (!value) continue;
84923
+ const listedName = listed.includes(key) ? key : listed.find((set2) => set2.toLowerCase() === name);
84924
+ return { name: listedName ?? key, value };
84925
+ }
84926
+ return void 0;
84927
+ }
84928
+ async function fetchWithRetry(operation, url2, init3, options = {}) {
84929
+ const settled = (status) => status < 500 || status === 503 && options.treat503AsFinal === true;
84930
+ const wrapped = (cause) => new ApiRequestError(
84931
+ `${operation}: couldn't reach ${new URL(url2).host}, ${describeFetchFailure(cause)}`,
84932
+ operation,
84933
+ null,
84934
+ { cause }
84935
+ );
84936
+ const request2 = withVersionHeader(init3);
84937
+ const answered = (response) => {
84938
+ responseOperations.set(response, operation);
84939
+ return response;
84940
+ };
84941
+ const delaysMs = options.retry === false ? [] : [250, 1e3];
84942
+ for (const delayMs of delaysMs) {
84943
+ try {
84944
+ const response = await fetch(url2, request2);
84945
+ if (settled(response.status)) return answered(response);
84946
+ } catch (cause) {
84947
+ if (isPoisonedHttp2Session(cause)) throw wrapped(cause);
84948
+ }
84949
+ await new Promise((resolve2) => setTimeout(resolve2, delayMs));
84950
+ }
84951
+ try {
84952
+ return answered(await fetch(url2, request2));
84953
+ } catch (cause) {
84954
+ throw wrapped(cause);
84955
+ }
84956
+ }
84957
+ var responseOperations = /* @__PURE__ */ new WeakMap();
84958
+ function responseOperation(response) {
84959
+ return responseOperations.get(response) ?? null;
84960
+ }
84961
+ var ApiRequestError = class extends Error {
84962
+ constructor(message2, operation, status, options) {
84963
+ super(message2, options);
84964
+ this.operation = operation;
84965
+ this.status = status;
84966
+ this.name = "ApiRequestError";
84967
+ }
84968
+ operation;
84969
+ status;
84970
+ };
84971
+ var RateLimitedError = class extends ApiRequestError {
84972
+ constructor(message2, retryAfterMs2, operation) {
84973
+ super(message2, operation, 429);
84974
+ this.retryAfterMs = retryAfterMs2;
84975
+ this.name = "RateLimitedError";
84976
+ }
84977
+ retryAfterMs;
84978
+ };
84979
+ function retryAfterMs(error63) {
84980
+ for (let cause = error63; cause instanceof Error; cause = cause.cause) {
84981
+ if (cause instanceof RateLimitedError) return cause.retryAfterMs;
84982
+ }
84983
+ return null;
84984
+ }
84985
+ function responseRequestId(response) {
84986
+ const parsed = apiRequestIdSchema.safeParse(response.headers.get("x-request-id"));
84987
+ return parsed.success ? parsed.data : null;
84988
+ }
84989
+ var failureRequestIds = /* @__PURE__ */ new WeakMap();
84990
+ function withRequestId(error63, response) {
84991
+ const requestId = responseRequestId(response);
84992
+ if (requestId !== null) failureRequestIds.set(error63, requestId);
84993
+ return error63;
84994
+ }
84995
+ function failureRequestId(error63) {
84996
+ for (let cause = error63; cause instanceof Error; cause = cause.cause) {
84997
+ const requestId = failureRequestIds.get(cause);
84998
+ if (requestId !== void 0) return requestId;
84999
+ }
85000
+ return null;
85001
+ }
85002
+ function parseRetryAfter(response) {
85003
+ const header = response.headers.get("retry-after");
85004
+ if (header === null) return null;
85005
+ const seconds = Number(header);
85006
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : null;
85007
+ }
85008
+ function zodIssueSummary(error63) {
85009
+ return error63.issues.map((issue2) => `${issue2.path.join(".") || "(root)"}: ${issue2.code}`).join("; ");
85010
+ }
85011
+ function describeFetchFailure(error63) {
85012
+ if (!(error63 instanceof Error)) return String(error63);
85013
+ return error63.cause instanceof Error && error63.cause.message ? error63.cause.message : error63.message;
85014
+ }
85015
+ function isPoisonedHttp2Session(error63) {
85016
+ let cursor = error63;
85017
+ for (let depth = 0; depth < 5 && cursor instanceof Error; depth += 1) {
85018
+ if (/session has been destroyed/i.test(cursor.message)) return true;
85019
+ cursor = cursor.cause;
85020
+ }
85021
+ return false;
85022
+ }
85023
+
84856
85024
  // ../../apps/syncservice/src/reporting.ts
84857
- function initCollectorReporting(appEnv, release2) {
85025
+ function initCollectorReporting(appEnv, release2, command) {
84858
85026
  const dsn = process.env.SENTRY_DSN;
84859
85027
  if (!dsn) return;
84860
85028
  init2({
@@ -84869,6 +85037,7 @@ function initCollectorReporting(appEnv, release2) {
84869
85037
  beforeBreadcrumb: (breadcrumb) => scrubBreadcrumb(breadcrumb)
84870
85038
  });
84871
85039
  setTag("service", "collector");
85040
+ if (command !== void 0) setTag("command", command);
84872
85041
  }
84873
85042
  var fetchTransport = (options) => createTransport(
84874
85043
  options,
@@ -84889,6 +85058,45 @@ function tagReportingIdentity(identity) {
84889
85058
  if (identity.orgId) setTag("org_id", identity.orgId);
84890
85059
  }
84891
85060
  var REPORT_AFTER_CONSECUTIVE_FAILURES = 3;
85061
+ var STREAK_REREPORT_INTERVAL_MS = 60 * 6e4;
85062
+ function failureStreak(report, now = Date.now, minDurationMs = 0) {
85063
+ let failures = 0;
85064
+ let firstAt = null;
85065
+ let reportedAt = -Infinity;
85066
+ return {
85067
+ failed(error63) {
85068
+ const at = now();
85069
+ firstAt ??= at;
85070
+ failures += 1;
85071
+ if (failures < REPORT_AFTER_CONSECUTIVE_FAILURES || at - firstAt < minDurationMs || at - reportedAt < STREAK_REREPORT_INTERVAL_MS) return;
85072
+ reportedAt = at;
85073
+ report(error63, { consecutiveFailures: failures });
85074
+ },
85075
+ succeeded() {
85076
+ failures = 0;
85077
+ firstAt = null;
85078
+ reportedAt = -Infinity;
85079
+ }
85080
+ };
85081
+ }
85082
+ function createRawUploadFailures(report, now = Date.now) {
85083
+ const failures = /* @__PURE__ */ new Map();
85084
+ return {
85085
+ failed(key, error63) {
85086
+ const streak = failures.get(key) ?? failureStreak(report, now, 6e4);
85087
+ failures.delete(key);
85088
+ failures.set(key, streak);
85089
+ if (failures.size > 1e3) {
85090
+ const oldest = failures.keys().next().value;
85091
+ if (oldest !== void 0) failures.delete(oldest);
85092
+ }
85093
+ streak.failed(error63);
85094
+ },
85095
+ succeeded(key) {
85096
+ failures.delete(key);
85097
+ }
85098
+ };
85099
+ }
84892
85100
  var ExpectedCliError = class extends Error {
84893
85101
  };
84894
85102
  var OFFLINE_ERROR_PATTERN = /couldn't reach|fetch failed|ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENETDOWN|ENETUNREACH|EHOSTUNREACH|headers timeout|socket hang up|session has been destroyed|other side closed/i;
@@ -84898,15 +85106,46 @@ function isOfflineError(error63) {
84898
85106
  }
84899
85107
  return false;
84900
85108
  }
84901
- function reportCollectorError(error63, operation, context2, level = "error") {
85109
+ function reportCollectorError(error63, operation, context2, level = "error", fingerprint) {
84902
85110
  if (error63 instanceof ExpectedCliError) return;
84903
85111
  const err = error63 instanceof Error ? error63 : new Error(String(error63));
85112
+ const request2 = apiRequestFailure(err);
85113
+ const requestId = failureRequestId(err);
85114
+ const grouping = fingerprint ?? (request2 === null ? void 0 : [
85115
+ "collector-api",
85116
+ request2.operation,
85117
+ request2.group,
85118
+ ...operation === "stuck-transcript-upload" ? ["persistent"] : [],
85119
+ ...request2.kind === "server-error" && requestId === null ? ["proxy"] : []
85120
+ ]);
85121
+ const actionable = operation === "stuck-transcript-upload" || (request2 === null ? !isOfflineError(err) : request2.kind === "rejected" || request2.group === "http2-pool-poisoned" || request2.kind === "server-error" && requestId === null);
84904
85122
  captureException(err, {
84905
- level: level === "warning" || isOfflineError(err) ? "warning" : "error",
84906
- tags: { service: "collector", operation },
85123
+ // A known request failure is classed by its kind, not its text: "capture-policy
85124
+ // fetch failed (400)" also matches the offline pattern.
85125
+ level: level === "warning" || (request2 === null ? isOfflineError(err) : request2.kind !== "rejected") ? "warning" : "error",
85126
+ tags: {
85127
+ service: "collector",
85128
+ operation,
85129
+ actionable,
85130
+ ...requestId === null ? {} : { request_id: requestId }
85131
+ },
85132
+ ...grouping === void 0 ? {} : { fingerprint: grouping },
84907
85133
  ...context2 ? { extra: context2 } : {}
84908
85134
  });
84909
85135
  }
85136
+ function apiRequestFailure(error63) {
85137
+ for (let cause = error63; cause instanceof Error; cause = cause.cause) {
85138
+ if (!(cause instanceof ApiRequestError)) continue;
85139
+ if (cause.status === null) {
85140
+ const group = isPoisonedHttp2Session(cause) ? "http2-pool-poisoned" : "unreachable";
85141
+ return { operation: cause.operation, kind: "unreachable", group };
85142
+ }
85143
+ if (cause.status >= 500) return { operation: cause.operation, kind: "server-error", group: "server-error" };
85144
+ if (cause.status === 429) return { operation: cause.operation, kind: "rate-limited", group: "429" };
85145
+ return { operation: cause.operation, kind: "rejected", group: String(cause.status) };
85146
+ }
85147
+ return null;
85148
+ }
84910
85149
  var REPORT_REPEAT_MS = 24 * 60 * 6e4;
84911
85150
  function dailyReporter(deps) {
84912
85151
  const sentAt = readMarker(deps.markerFile, deps.readTextFile, deps.now);
@@ -85131,148 +85370,6 @@ function readRecord(recordPath, roots) {
85131
85370
 
85132
85371
  // ../../apps/syncservice/src/diagnostics.ts
85133
85372
  import { createHmac } from "node:crypto";
85134
-
85135
- // ../../apps/syncservice/src/http.ts
85136
- import tls2 from "node:tls";
85137
- var import_undici = __toESM(require_undici(), 1);
85138
- var CLI_VERSION_HEADER = "x-powerplant-cli-version";
85139
- var cliVersion = true ? "0.4.27" : "0.0.0-checkout";
85140
- function cliVersionHeaders() {
85141
- return { [CLI_VERSION_HEADER]: cliVersion, "user-agent": `powerplant-cli/${cliVersion}` };
85142
- }
85143
- function withVersionHeader(init3) {
85144
- const headers = new Headers(init3?.headers);
85145
- for (const [name, value] of Object.entries(cliVersionHeaders())) headers.set(name, value);
85146
- return { ...init3, headers };
85147
- }
85148
- function installHttpTransport(env, certificates = tls2) {
85149
- trustSystemCertificates(certificates);
85150
- const { ignored, ...settings } = proxySettings(env);
85151
- (0, import_undici.setGlobalDispatcher)(new import_undici.EnvHttpProxyAgent({ allowH2: false, ...settings }));
85152
- if (ignored.length === 0) return null;
85153
- return `Powerplant ignores ${ignored.join(" and ")}. It can use only an address like http://user:password@proxy.example.com:8080. Write a % in a password as %25.`;
85154
- }
85155
- function trustSystemCertificates(store) {
85156
- const { getCACertificates, setDefaultCACertificates } = store;
85157
- if (getCACertificates === void 0 || setDefaultCACertificates === void 0) return;
85158
- const defaults = getCACertificates("default");
85159
- const current = new Set(defaults);
85160
- if (!getCACertificates("bundled").every((root) => current.has(root))) return;
85161
- setDefaultCACertificates([...defaults, ...getCACertificates("system")]);
85162
- }
85163
- function proxySettings(env) {
85164
- const ignored = [];
85165
- const address = (name) => {
85166
- const found = environmentVariable(env, name);
85167
- if (found === void 0) return "";
85168
- const value = /^[a-z][a-z\d+.-]*:\/\//i.test(found.value) ? found.value : `http://${found.value}`;
85169
- const url2 = URL.canParse(value) ? new URL(value) : null;
85170
- const usable = url2 !== null && ["http:", "https:"].includes(url2.protocol) && url2.username === "" === (url2.password === "") && undiciAccepts(value);
85171
- if (usable) return value;
85172
- ignored.push(found.name);
85173
- return "";
85174
- };
85175
- return {
85176
- httpProxy: address("http_proxy"),
85177
- httpsProxy: address("https_proxy"),
85178
- noProxy: environmentVariable(env, "no_proxy")?.value ?? "",
85179
- ignored
85180
- };
85181
- }
85182
- function undiciAccepts(address) {
85183
- try {
85184
- void new import_undici.ProxyAgent(address).close();
85185
- return true;
85186
- } catch {
85187
- return false;
85188
- }
85189
- }
85190
- function environmentVariable(env, name) {
85191
- const listed = Object.keys(env);
85192
- for (const key of [name, name.toUpperCase()]) {
85193
- const value = env[key]?.trim();
85194
- if (!value) continue;
85195
- const listedName = listed.includes(key) ? key : listed.find((set2) => set2.toLowerCase() === name);
85196
- return { name: listedName ?? key, value };
85197
- }
85198
- return void 0;
85199
- }
85200
- async function fetchWithRetry(operation, url2, init3, options = {}) {
85201
- const settled = (status) => status < 500 || status === 503 && options.treat503AsFinal === true;
85202
- const wrapped = (cause) => new Error(`${operation}: couldn't reach ${new URL(url2).host}, ${describeFetchFailure(cause)}`, {
85203
- cause
85204
- });
85205
- const request2 = withVersionHeader(init3);
85206
- const delaysMs = options.retry === false ? [] : [250, 1e3];
85207
- for (const delayMs of delaysMs) {
85208
- try {
85209
- const response = await fetch(url2, request2);
85210
- if (settled(response.status)) return response;
85211
- } catch (cause) {
85212
- if (isPoisonedHttp2Session(cause)) throw wrapped(cause);
85213
- }
85214
- await new Promise((resolve2) => setTimeout(resolve2, delayMs));
85215
- }
85216
- try {
85217
- return await fetch(url2, request2);
85218
- } catch (cause) {
85219
- throw wrapped(cause);
85220
- }
85221
- }
85222
- var RateLimitedError = class extends Error {
85223
- constructor(message2, retryAfterMs2) {
85224
- super(message2);
85225
- this.retryAfterMs = retryAfterMs2;
85226
- this.name = "RateLimitedError";
85227
- }
85228
- retryAfterMs;
85229
- };
85230
- function retryAfterMs(error63) {
85231
- for (let cause = error63; cause instanceof Error; cause = cause.cause) {
85232
- if (cause instanceof RateLimitedError) return cause.retryAfterMs;
85233
- }
85234
- return null;
85235
- }
85236
- function responseRequestId(response) {
85237
- const parsed = apiRequestIdSchema.safeParse(response.headers.get("x-request-id"));
85238
- return parsed.success ? parsed.data : null;
85239
- }
85240
- var failureRequestIds = /* @__PURE__ */ new WeakMap();
85241
- function withRequestId(error63, response) {
85242
- const requestId = responseRequestId(response);
85243
- if (requestId !== null) failureRequestIds.set(error63, requestId);
85244
- return error63;
85245
- }
85246
- function failureRequestId(error63) {
85247
- for (let cause = error63; cause instanceof Error; cause = cause.cause) {
85248
- const requestId = failureRequestIds.get(cause);
85249
- if (requestId !== void 0) return requestId;
85250
- }
85251
- return null;
85252
- }
85253
- function parseRetryAfter(response) {
85254
- const header = response.headers.get("retry-after");
85255
- if (header === null) return null;
85256
- const seconds = Number(header);
85257
- return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : null;
85258
- }
85259
- function zodIssueSummary(error63) {
85260
- return error63.issues.map((issue2) => `${issue2.path.join(".") || "(root)"}: ${issue2.code}`).join("; ");
85261
- }
85262
- function describeFetchFailure(error63) {
85263
- if (!(error63 instanceof Error)) return String(error63);
85264
- return error63.cause instanceof Error && error63.cause.message ? error63.cause.message : error63.message;
85265
- }
85266
- function isPoisonedHttp2Session(error63) {
85267
- let cursor = error63;
85268
- for (let depth = 0; depth < 5 && cursor instanceof Error; depth += 1) {
85269
- if (/session has been destroyed/i.test(cursor.message)) return true;
85270
- cursor = cursor.cause;
85271
- }
85272
- return false;
85273
- }
85274
-
85275
- // ../../apps/syncservice/src/diagnostics.ts
85276
85373
  function observeFileDiagnostic(observer, file2) {
85277
85374
  try {
85278
85375
  observer?.(file2);
@@ -88553,8 +88650,9 @@ function nativeHarnessName(harness) {
88553
88650
  throw new Error(`unsupported hook harness: ${String(harness)}`);
88554
88651
  }
88555
88652
  }
88653
+ var CODEX_EVENTS = ["SessionStart", "SessionEnd", "Stop"];
88556
88654
  function harnessEvents(harness) {
88557
- return nativeHarnessName(harness) === "cursor" ? ["sessionStart", "sessionEnd", "stop"] : ["SessionStart", "SessionEnd", "Stop"];
88655
+ return nativeHarnessName(harness) === "cursor" ? ["sessionStart", "sessionEnd", "stop"] : CODEX_EVENTS;
88558
88656
  }
88559
88657
  function harnessHookConfigPath(harness, home) {
88560
88658
  const nativeName = nativeHarnessName(harness);
@@ -88592,15 +88690,19 @@ function isOurHook2(hook) {
88592
88690
  if (runsPowerplantHook(commandWords(command) ?? [])) return true;
88593
88691
  return /['"]$/.test(command) && OUR_LEGACY_SCRIPTS.includes(command.slice(0, -1).split(/[\\/]/).pop());
88594
88692
  }
88595
- var CODEX_HOOK_NAME = "Powerplant";
88596
- function codexHandler(command, entries, kept) {
88693
+ var CODEX_HOOK_NAMES = {
88694
+ SessionStart: "Powerplant: Session Start",
88695
+ Stop: "Powerplant: Turn End",
88696
+ SessionEnd: "Powerplant: Session End"
88697
+ };
88698
+ function codexHandler(event, command, entries, kept) {
88597
88699
  const last = entries.at(-1);
88598
88700
  const inPlace = last !== void 0 && kept.length === entries.length - 1 && Object.keys(last).length === 1 ? external_exports.array(jsonObject).parse(last.hooks) : [];
88599
88701
  const current = inPlace.length === 1 ? inPlace[0] : void 0;
88600
88702
  if (current !== void 0 && current.type === "command" && current.command === command && current.timeout === 2 && Object.keys(current).every((key) => ["type", "command", "timeout", "statusMessage"].includes(key))) {
88601
88703
  return current;
88602
88704
  }
88603
- return { type: "command", command, timeout: 2, statusMessage: CODEX_HOOK_NAME };
88705
+ return { type: "command", command, timeout: 2, statusMessage: CODEX_HOOK_NAMES[event] };
88604
88706
  }
88605
88707
  function mergeHarnessHooks(harness, text, command) {
88606
88708
  try {
@@ -88630,7 +88732,7 @@ function mergeHarnessHooks(harness, text, command) {
88630
88732
  else hooks[event] = kept;
88631
88733
  continue;
88632
88734
  }
88633
- const handler = nativeName === "cursor" ? { command, timeout: 2 } : codexHandler(command, entries, kept);
88735
+ const handler = nativeName === "cursor" ? { command, timeout: 2 } : codexHandler(event, command, entries, kept);
88634
88736
  hooks[event] = [...kept, nativeName === "cursor" ? handler : { hooks: [handler] }];
88635
88737
  }
88636
88738
  const next = { ...settings, ...nativeName === "cursor" && command !== null ? { version: 1 } : {}, hooks };
@@ -88942,7 +89044,8 @@ function createHookHealthTracker(deps) {
88942
89044
  installedAt: new Date(installedAtMs).toISOString(),
88943
89045
  sessionStartedAfterInstallMs: Date.parse(candidate.startedAt) - installedAtMs
88944
89046
  },
88945
- "warning"
89047
+ "warning",
89048
+ ["collector-hook-silent", harness, silence.kind]
88946
89049
  );
88947
89050
  }
88948
89051
  return true;
@@ -89658,9 +89761,10 @@ function readServiceProcess(appEnv) {
89658
89761
  });
89659
89762
  } catch (cause) {
89660
89763
  const status = cause instanceof Error && "status" in cause ? cause.status : void 0;
89764
+ const timedOut = cause instanceof Error && "code" in cause && cause.code === "ETIMEDOUT";
89661
89765
  if (status === 112) return { kind: "domain-missing" };
89662
89766
  if (status === 113) return { kind: "absent" };
89663
- throw new Error(`Could not verify the background sync process: ${typeof status === "number" ? describeLaunchctlExit(status) : "launchctl failed or timed out"}`);
89767
+ throw new Error(`Could not verify the background sync process: ${timedOut ? "launchctl did not answer within 3 s" : typeof status === "number" ? describeLaunchctlExit(status) : "launchctl failed or timed out"}`);
89664
89768
  }
89665
89769
  const match = /^\s*pid = (\d+)\s*$/m.exec(output2);
89666
89770
  return { kind: "loaded", pid: match ? Number(match[1]) : null };
@@ -89677,7 +89781,7 @@ function refuseStaleAppEnvLauncher(env, readLauncher = readLauncherIfExists) {
89677
89781
  const script = readLauncher(launcherPath(appEnv));
89678
89782
  if (script === null || !script.includes("APP_ENV=") || script.includes("POWERPLANT_ENV=")) return;
89679
89783
  throw new ExpectedCliError(
89680
- `This background service was installed before the POWERPLANT_ENV rename and is no longer supported. Remove it with: powerplant uninstall --env ${appEnv}` + (appEnv === "production" ? ", then powerplant init reinstalls it." : `, then powerplant init --env ${appEnv} reinstalls it if you still need it.`)
89784
+ `This background service was installed before the POWERPLANT_ENV rename and is no longer supported. ` + (appEnv === "production" ? "Remove it with: powerplant uninstall, then powerplant init reinstalls it." : `Remove it with: powerplant uninstall --env ${appEnv}, then powerplant init --env ${appEnv} reinstalls it if you still need it.`)
89681
89785
  );
89682
89786
  }
89683
89787
  function readLauncherIfExists(launcherFile) {
@@ -89913,11 +90017,11 @@ function readInstallRecord(file2) {
89913
90017
  return { kind: "found", record: parsed.data };
89914
90018
  }
89915
90019
  function writeInstallRecord(file2, record2) {
89916
- const checked = installRecordSchema.parse(record2);
90020
+ const checked2 = installRecordSchema.parse(record2);
89917
90021
  const temporary = `${file2}.${process.pid}.tmp`;
89918
90022
  try {
89919
90023
  mkdirSync8(path16.dirname(file2), { recursive: true });
89920
- writeFileSync7(temporary, `${JSON.stringify(checked, null, 2)}
90024
+ writeFileSync7(temporary, `${JSON.stringify(checked2, null, 2)}
89921
90025
  `);
89922
90026
  renameSync6(temporary, file2);
89923
90027
  } catch (error63) {
@@ -90042,8 +90146,9 @@ var EncryptedCredentialStore = class {
90042
90146
  };
90043
90147
  function unreadableCredentials(appEnv, reason) {
90044
90148
  const powerplant = typedPowerplantCommand(appEnv);
90149
+ const env = appEnv === "production" ? "" : ` --env ${appEnv}`;
90045
90150
  return new ExpectedCliError(
90046
- `Stored sync service credentials for ${appEnv} cannot be read: ${reason}. Run ${powerplant} uninstall --forget --env ${appEnv}, then ${powerplant} init --env ${appEnv} to re-enroll.`
90151
+ `Stored sync service credentials for ${appEnv} cannot be read: ${reason}. Run ${powerplant} uninstall --forget${env}, then ${powerplant} init${env} to re-enroll.`
90047
90152
  );
90048
90153
  }
90049
90154
  function writeNewFile(file2, content) {
@@ -90679,6 +90784,7 @@ var TaskSchedulerService = class {
90679
90784
  this.homeDir = homeDir;
90680
90785
  this.env = deps.env ?? process.env;
90681
90786
  this.runPowerShell = deps.runPowerShell ?? runWindowsPowerShell;
90787
+ this.runPowerShellAsync = deps.runPowerShellAsync ?? runWindowsPowerShellAsync;
90682
90788
  this.endProcess = deps.endProcess ?? endProcessIfRunning;
90683
90789
  this.isElevated = deps.isElevated ?? (() => windowsProcessIsElevated(this.env.SystemRoot ?? "C:\\Windows"));
90684
90790
  this.taskNameInput = { taskBaseName: serviceDisplayName(appEnv), profilePath: homeDir };
@@ -90694,6 +90800,7 @@ var TaskSchedulerService = class {
90694
90800
  definitionPath;
90695
90801
  env;
90696
90802
  runPowerShell;
90803
+ runPowerShellAsync;
90697
90804
  endProcess;
90698
90805
  /** The input every script builds the task name from (TASK_NAME_PRELUDE). */
90699
90806
  taskNameInput;
@@ -90705,9 +90812,15 @@ var TaskSchedulerService = class {
90705
90812
  * way. */
90706
90813
  state() {
90707
90814
  if (!existsSync8(this.definitionPath)) return "not-installed";
90708
- const { task } = this.describe(null);
90709
- if (task === null) return "not-installed";
90710
- return task.state === "Running" ? "loaded" : "not-loaded";
90815
+ return taskState(this.describe(null).task);
90816
+ }
90817
+ /** state() without blocking, so status and doctor can ask Task Scheduler
90818
+ * while they unlock the credentials and wait for the network. */
90819
+ async stateAsync() {
90820
+ if (!existsSync8(this.definitionPath)) return "not-installed";
90821
+ const record2 = readSupervisorRecord(this.recordPath);
90822
+ const result = await this.runPowerShellAsync(DESCRIBE_SCRIPT, JSON.stringify(this.describeInput(null, record2)));
90823
+ return taskState(this.described(record2, checked("read the task", result)).task);
90711
90824
  }
90712
90825
  /** Registered with this command and this definition, and running. */
90713
90826
  upToDate(command) {
@@ -90865,12 +90978,17 @@ var TaskSchedulerService = class {
90865
90978
  * recorded program. */
90866
90979
  describe(action) {
90867
90980
  const record2 = readSupervisorRecord(this.recordPath);
90981
+ return this.described(record2, this.run("read the task", DESCRIBE_SCRIPT, this.describeInput(action, record2)));
90982
+ }
90983
+ describeInput(action, record2) {
90868
90984
  const expected = action === null ? null : { ...action, description: this.description() };
90869
- const result = this.run("read the task", DESCRIBE_SCRIPT, {
90985
+ return {
90870
90986
  ...this.taskNameInput,
90871
90987
  expected,
90872
90988
  supervisor: record2 === null ? null : { pid: record2.pid, executable: record2.executable }
90873
- });
90989
+ };
90990
+ }
90991
+ described(record2, result) {
90874
90992
  const parsed = describeOutputSchema.safeParse(parseJson(result.stdout));
90875
90993
  if (!parsed.success) throw new Error("Task Scheduler returned an answer this version cannot read");
90876
90994
  const running = parsed.data.supervisor;
@@ -90890,11 +91008,17 @@ var TaskSchedulerService = class {
90890
91008
  if (described.supervisorPid !== null) this.endProcess(described.supervisorPid);
90891
91009
  }
90892
91010
  run(step, script, input2) {
90893
- const result = this.runPowerShell(script, JSON.stringify(input2));
90894
- if (result.status !== 0) throw new Error(`Task Scheduler could not ${step}: ${powerShellError(result)}`);
90895
- return result;
91011
+ return checked(step, this.runPowerShell(script, JSON.stringify(input2)));
90896
91012
  }
90897
91013
  };
91014
+ function checked(step, result) {
91015
+ if (result.status !== 0) throw new Error(`Task Scheduler could not ${step}: ${powerShellError(result)}`);
91016
+ return result;
91017
+ }
91018
+ function taskState(task) {
91019
+ if (task === null) return "not-installed";
91020
+ return task.state === "Running" ? "loaded" : "not-loaded";
91021
+ }
90898
91022
  var describeOutputSchema = external_exports.object({
90899
91023
  taskName: external_exports.string(),
90900
91024
  task: external_exports.object({ state: external_exports.string(), current: external_exports.boolean() }).nullable(),
@@ -91992,14 +92116,19 @@ async function errorDetail(response) {
91992
92116
  }
91993
92117
  const parsed = errorDetailSchema.safeParse(body);
91994
92118
  const trimmed = text.trim();
91995
- const detail = parsed.success ? parsed.data.error : trimmed === "" ? "no detail" : trimmed.slice(0, 200);
92119
+ const detail = parsed.success ? parsed.data.error : trimmed === "" ? "no detail" : trimmed.startsWith("<") ? htmlPageDetail(trimmed) : trimmed.slice(0, 200);
91996
92120
  const requestId = responseRequestId(response) ?? (parsed.success ? parsed.data.meta?.requestId : void 0);
91997
92121
  return requestId === void 0 ? detail : `${detail} [request ${requestId}]`;
91998
92122
  }
92123
+ function htmlPageDetail(page) {
92124
+ const title = htmlPageTitle(page);
92125
+ return `the server sent an error page${title ? ` ("${title}")` : ""}`;
92126
+ }
91999
92127
  async function failedResponse(label2, response) {
92000
92128
  const message2 = `${label2} (${response.status}): ${await errorDetail(response)}`;
92129
+ const operation = responseOperation(response) ?? label2;
92001
92130
  return withRequestId(
92002
- response.status === 429 ? new RateLimitedError(message2, parseRetryAfter(response)) : new Error(message2),
92131
+ response.status === 429 ? new RateLimitedError(message2, parseRetryAfter(response), operation) : new ApiRequestError(message2, operation, response.status),
92003
92132
  response
92004
92133
  );
92005
92134
  }
@@ -92289,12 +92418,10 @@ async function uploadRawSessions(apiUrl, machineToken, transcriptUploadSources,
92289
92418
  summary.outcomes.set(key, "missing-metadata");
92290
92419
  continue;
92291
92420
  }
92292
- if (response.status === 429) {
92293
- throw await failedResponse("raw transcript upload failed", response);
92294
- }
92295
92421
  if (!response.ok) {
92296
- throw new Error(`${response.status}: ${await errorDetail(response)}`);
92422
+ throw await failedResponse("raw transcript upload failed", response);
92297
92423
  }
92424
+ progress?.failures?.succeeded(key);
92298
92425
  summary.uploaded += 1;
92299
92426
  summary.skippedSubagentFiles += skippedSubagentFiles;
92300
92427
  summary.outcomes.set(key, "uploaded");
@@ -92310,8 +92437,10 @@ async function uploadRawSessions(apiUrl, machineToken, transcriptUploadSources,
92310
92437
  summary.outcomes.set(key, "changed-since-read");
92311
92438
  continue;
92312
92439
  }
92440
+ progress?.failures?.failed(key, error63);
92313
92441
  summary.outcomes.set(key, "failed");
92314
92442
  if (error63 instanceof RateLimitedError) rateLimited ??= error63;
92443
+ summary.firstFailure ??= error63;
92315
92444
  summary.failed.push(
92316
92445
  `${session.item.harnessSessionId}: ${error63 instanceof Error ? error63.message : String(error63)}`
92317
92446
  );
@@ -92511,7 +92640,11 @@ async function redeemApproval(apiUrl, code, verifier) {
92511
92640
  }
92512
92641
  async function readEnrollmentResponse(response) {
92513
92642
  if (response.status !== 201) {
92514
- throw new Error(`enrollment failed (${response.status}): ${await errorDetail(response)}`);
92643
+ throw withRequestId(new ApiRequestError(
92644
+ `enrollment failed (${response.status}): ${await errorDetail(response)}`,
92645
+ responseOperation(response) ?? "enrolling this machine",
92646
+ response.status
92647
+ ), response);
92515
92648
  }
92516
92649
  const body = await response.json().catch(() => null);
92517
92650
  const enrollment = body?.data;
@@ -94340,6 +94473,11 @@ function requireBackgroundService(service) {
94340
94473
  function serviceState2(config2) {
94341
94474
  return hostBackgroundService(config2.appEnv)?.state() ?? "unsupported";
94342
94475
  }
94476
+ async function serviceStateAsync(config2) {
94477
+ const service = hostBackgroundService(config2.appEnv);
94478
+ if (service === null) return "unsupported";
94479
+ return service.stateAsync === void 0 ? service.state() : service.stateAsync();
94480
+ }
94343
94481
  function serviceUpToDate2(config2, command) {
94344
94482
  return hostBackgroundService(config2.appEnv)?.upToDate(command) ?? false;
94345
94483
  }
@@ -94791,7 +94929,8 @@ async function runSyncPassInternal(config2, options, diagnostic, turn) {
94791
94929
  options.rawShipped,
94792
94930
  {
94793
94931
  beforeUpload: options.beforeRawUpload ? () => options.beforeRawUpload(collected) : void 0,
94794
- onUploaded: options.onRawUploaded
94932
+ onUploaded: options.onRawUploaded,
94933
+ failures: options.rawUploadFailures
94795
94934
  }
94796
94935
  );
94797
94936
  const givenUp = options.codexThreadLinks?.settleRecoveries((session) => {
@@ -94838,7 +94977,9 @@ async function runSyncPassInternal(config2, options, diagnostic, turn) {
94838
94977
  }
94839
94978
  const nothingElseAccountedFor = raw.skippedUnchanged === 0 && raw.skippedTooLarge === 0 && rawWindowSkipped === 0 && raw.missingMetadata === 0 && raw.changedSinceRead === 0;
94840
94979
  if (raw.uploaded === 0 && (raw.failed.length > 1 || raw.failed.length === 1 && nothingElseAccountedFor)) {
94841
- throw new Error(`all ${raw.failed.length} raw upload(s) failed this pass, ${raw.failed[0]}`);
94980
+ throw new Error(`all ${raw.failed.length} raw upload(s) failed this pass, ${raw.failed[0]}`, {
94981
+ cause: raw.firstFailure
94982
+ });
94842
94983
  }
94843
94984
  if (deferred > 0 || claimsUnresolved) {
94844
94985
  if (window2.deepSweep) {
@@ -95336,7 +95477,6 @@ var NARROW_OVERLAP_MS = 6e4;
95336
95477
  var WATCHER_RETRY_MS = 6e4;
95337
95478
  var FAILED_PASS_RETRY_MS = 6e4;
95338
95479
  var FAILED_PASS_BACKOFF_CAP_MS = 15 * 6e4;
95339
- var STREAK_REREPORT_INTERVAL_MS = 60 * 6e4;
95340
95480
  var VERSION_NOTICE_INTERVAL_MS = 60 * 6e4;
95341
95481
  var COMPLETION_SLACK_MS = 3e4;
95342
95482
  function createWatchLoop(deps) {
@@ -95692,6 +95832,7 @@ function watchSessionStores(roots, onEvent, onLost) {
95692
95832
  }
95693
95833
  function newSessionSyncOptions(shared, sinceMs, isNew) {
95694
95834
  return {
95835
+ rawUploadFailures: shared.rawUploadFailures,
95695
95836
  lifecycleJournal: shared.lifecycleJournal,
95696
95837
  log: shared.log,
95697
95838
  enrollCommand: shared.enrollCommand,
@@ -95871,17 +96012,24 @@ function startWatch(config2, homeDir, runtime = { version: "checkout" }) {
95871
96012
  onChecked: () => menu?.changed()
95872
96013
  });
95873
96014
  const rawShipped = /* @__PURE__ */ new Map();
96015
+ const rawUploadFailures = createRawUploadFailures(
96016
+ (error63, context2) => reportCollectorError(error63, "stuck-transcript-upload", context2)
96017
+ );
95874
96018
  const codexThreadLinks = new CodexThreadLinks();
95875
96019
  const codexThreadReads = new CodexThreadReads();
95876
96020
  const recordTurns = new RecordTurns();
96021
+ const catchUpFailures = failureStreak(
96022
+ (error63, context2) => reportCollectorError(error63, "recent-session-catchup", context2)
96023
+ );
95877
96024
  const loop = createWatchLoop({
95878
96025
  runPass: async (options) => {
95879
96026
  let uploaded = 0;
95880
96027
  let activeSinceMs = Infinity;
95881
96028
  const activeSessions = /* @__PURE__ */ new Set();
95882
- let lastCatchupReportAt = -Infinity;
96029
+ let catchUpFailedThisPass = false;
95883
96030
  const shared = {
95884
96031
  rawShipped,
96032
+ rawUploadFailures,
95885
96033
  codexThreadLinks,
95886
96034
  codexThreadReads,
95887
96035
  lifecycleJournal: journal,
@@ -95904,6 +96052,7 @@ function startWatch(config2, homeDir, runtime = { version: "checkout" }) {
95904
96052
  Math.min(narrowSinceMs, activeSinceMs),
95905
96053
  { sinceMs: narrowSinceMs, sessions: activeSessions }
95906
96054
  ));
96055
+ catchUpFailures.succeeded();
95907
96056
  activeSinceMs = recentCatchupFloor(activeSinceMs, recent.sessions);
95908
96057
  for (const session of recent.sessions) {
95909
96058
  if (session.item.status === "active") activeSessions.add(sessionKey(session.item));
@@ -95923,10 +96072,8 @@ function startWatch(config2, homeDir, runtime = { version: "checkout" }) {
95923
96072
  await catchUp();
95924
96073
  } catch (error63) {
95925
96074
  log3(`Recent session catch-up failed, history continues: ${describeError(error63)}`);
95926
- if (Date.now() - lastCatchupReportAt >= STREAK_REREPORT_INTERVAL_MS) {
95927
- lastCatchupReportAt = Date.now();
95928
- reportCollectorError(error63, "recent-session-catchup");
95929
- }
96075
+ if (!catchUpFailedThisPass) catchUpFailures.failed(error63);
96076
+ catchUpFailedThisPass = true;
95930
96077
  }
95931
96078
  return uploaded - beforeCatchup;
95932
96079
  }
@@ -95940,6 +96087,7 @@ function startWatch(config2, homeDir, runtime = { version: "checkout" }) {
95940
96087
  return summary;
95941
96088
  },
95942
96089
  runNewSessionPass: ({ sinceMs, isNew }) => runSyncPass(config2, newSessionSyncOptions({
96090
+ rawUploadFailures,
95943
96091
  lifecycleJournal: journal,
95944
96092
  log: log3,
95945
96093
  enrollCommand: runtime.enrollCommand,
@@ -96672,7 +96820,7 @@ import { accessSync, constants as constants4, readFileSync as readFileSync22 } f
96672
96820
  import path42 from "node:path";
96673
96821
 
96674
96822
  // src/version.ts
96675
- var CLI_VERSION = true ? "0.4.27" : "0.0.0-checkout";
96823
+ var CLI_VERSION = true ? "0.4.28" : "0.0.0-checkout";
96676
96824
  var CLI_RELEASE_BUILD = true ? true : false;
96677
96825
  var CLI_PACKAGE_NAME = "@usepowerplant/cli";
96678
96826
 
@@ -100004,12 +100152,12 @@ function mcpBlock(i, connection) {
100004
100152
  const name = `${AGENT_DISPLAY_NAMES[connection.client]}${connection.target ? ` (${connection.target})` : ""}`;
100005
100153
  const fix = `Run ${run(i, `connect --client ${connection.client}`)}.`;
100006
100154
  const current = connectionIsCurrent(connection, i.now);
100007
- const checked = current ? "" : `, checked ${ago(i.now - Date.parse(connection.checkedAt))}`;
100155
+ const checked2 = current ? "" : `, checked ${ago(i.now - Date.parse(connection.checkedAt))}`;
100008
100156
  switch (connection.state) {
100009
100157
  case "signed-in":
100010
- return block(`${current ? "\u2713 " : ""}${name}: MCP connected${checked}`);
100158
+ return block(`${current ? "\u2713 " : ""}${name}: MCP connected${checked2}`);
100011
100159
  case "sign-in-needed":
100012
- return block(`! ${name}: MCP sign-in needed${checked}`, fix);
100160
+ return block(`! ${name}: MCP sign-in needed${checked2}`, fix);
100013
100161
  case "different-url":
100014
100162
  return block(
100015
100163
  `! ${name}: MCP points at a different Powerplant${connection.registeredUrl ? `, ${connection.registeredUrl}` : ""}`,
@@ -100111,6 +100259,11 @@ async function fetchNewestRelease(packageName, fetchImpl = fetch) {
100111
100259
  function releaseSource(appEnv) {
100112
100260
  return appEnv === "production" ? "promoted" : "npm";
100113
100261
  }
100262
+ function fetchVersionFacts(appEnv, credentials, packageName, fetchImpl = fetch) {
100263
+ const policy = credentials === null ? Promise.resolve(null) : fetchVersionPolicy(credentials.apiUrl, credentials.token, fetchImpl);
100264
+ const latest2 = releaseSource(appEnv) === "npm" ? fetchNewestRelease(packageName, fetchImpl) : policy.then((found) => found?.promotedVersion ?? null);
100265
+ return Promise.all([latest2, policy.then((found) => found?.oldestSupportedVersion ?? null)]);
100266
+ }
100114
100267
 
100115
100268
  // src/terminal.ts
100116
100269
  var ANSI = {
@@ -100156,6 +100309,13 @@ function styleUrls(line) {
100156
100309
  function styleCommands(line) {
100157
100310
  return line.replace(/`([^`]+)`/g, (_, command) => `${ANSI.bold}${command}${ANSI.resetDim}`);
100158
100311
  }
100312
+ function ignoreClosedOutput(streams) {
100313
+ for (const stream of streams) {
100314
+ stream.on("error", (error63) => {
100315
+ if (error63.code !== "EPIPE") throw error63;
100316
+ });
100317
+ }
100318
+ }
100159
100319
  function dim(line) {
100160
100320
  return `${ANSI.dim}${line}${ANSI.resetDim}`;
100161
100321
  }
@@ -101244,6 +101404,7 @@ function parseCliArgs() {
101244
101404
  });
101245
101405
  }
101246
101406
  async function main() {
101407
+ ignoreClosedOutput([process.stdout, process.stderr]);
101247
101408
  if (isNpmCopyOnWindows(process.platform, entryPath())) {
101248
101409
  const { values: values2 } = parseArgs({ strict: false, allowPositionals: true, options: { env: { type: "string" } } });
101249
101410
  const config3 = resolveCliConfig(process.env, typeof values2.env === "string" ? values2.env : void 0);
@@ -101286,7 +101447,7 @@ ${USAGE}`);
101286
101447
  }
101287
101448
  const dsn = reportingDsn(process.env, config2, CLI_RELEASE_BUILD);
101288
101449
  if (dsn !== void 0) process.env.SENTRY_DSN = dsn;
101289
- initCollectorReporting(config2.appEnv, CLI_VERSION);
101450
+ initCollectorReporting(config2.appEnv, CLI_VERSION, CLI_COMMANDS.has(cliCommand) ? cliCommand : "unknown");
101290
101451
  const proxyNotice = installHttpTransport(process.env);
101291
101452
  if (proxyNotice !== null) console.error(styledFor(process.stderr)(proxyNotice));
101292
101453
  const menuStages = menuStageClock();
@@ -101558,28 +101719,33 @@ The access you granted these agents stays on your Powerplant account until you r
101558
101719
  return;
101559
101720
  }
101560
101721
  case "status": {
101561
- const stored = loadCredentialsSafely(config2);
101562
- const credentials = stored.credentials;
101563
- const [latestVersion, oldestSupportedVersion, protectedSessions] = await Promise.all([
101564
- fetchAvailableVersion(config2, credentials),
101565
- oldestSupportedFor(credentials),
101566
- process.platform === "darwin" && credentials ? findRecentProtectedSessions({
101567
- environment: { allowedProtectedRoots: credentials.repoDiscoveryRoots ?? [] }
101568
- }).then(
101569
- (found) => found.filter((entry) => protectedRootReview(credentials, entry.root) !== "allowed")
101570
- ) : []
101571
- ]);
101722
+ const read = async () => {
101723
+ const service = readServiceSafelyAsync(config2);
101724
+ const stored = loadCredentialsSafely(config2);
101725
+ const credentials = stored.credentials;
101726
+ const [[latestVersion, oldestSupportedVersion], protectedSessions, serviceRead] = await Promise.all([
101727
+ fetchVersionFacts(config2.appEnv, credentials, CLI_PACKAGE_NAME),
101728
+ process.platform === "darwin" && credentials ? findRecentProtectedSessions({
101729
+ environment: { allowedProtectedRoots: credentials.repoDiscoveryRoots ?? [] }
101730
+ }).then(
101731
+ (found2) => found2.filter((entry) => protectedRootReview(credentials, entry.root) !== "allowed")
101732
+ ) : [],
101733
+ service
101734
+ ]);
101735
+ return { stored, latestVersion, oldestSupportedVersion, protectedSessions, serviceRead };
101736
+ };
101737
+ const found = values.json ? await read() : await terminal.command.activity("Checking sync status\u2026", read);
101572
101738
  const inputs = {
101573
101739
  config: config2,
101574
101740
  cliVersion: CLI_VERSION,
101575
- ...stored,
101576
- ...readServiceSafely(config2),
101741
+ ...found.stored,
101742
+ ...found.serviceRead,
101577
101743
  ...readCredentialStoreSafely(config2),
101578
101744
  daemon: describeDaemonState(readCollectorStatus(config2.appEnv)),
101579
101745
  control: readCollectorControl(config2.appEnv),
101580
- latestVersion,
101581
- oldestSupportedVersion,
101582
- protectedSessions,
101746
+ latestVersion: found.latestVersion,
101747
+ oldestSupportedVersion: found.oldestSupportedVersion,
101748
+ protectedSessions: found.protectedSessions,
101583
101749
  connections: readHarnessConnections(config2.appEnv, realReadTextFile),
101584
101750
  ...readMcpPreferencesForMenu(config2.appEnv),
101585
101751
  now: Date.now()
@@ -101589,22 +101755,26 @@ The access you granted these agents stays on your Powerplant account until you r
101589
101755
  return;
101590
101756
  }
101591
101757
  case "doctor": {
101592
- const stored = loadCredentialsSafely(config2);
101593
- const [latestVersion, oldestSupportedVersion] = await Promise.all([
101594
- fetchAvailableVersion(config2, stored.credentials),
101595
- oldestSupportedFor(stored.credentials)
101596
- ]);
101758
+ const found = await terminal.command.activity("Collecting diagnostics\u2026", async () => {
101759
+ const service = readServiceSafelyAsync(config2);
101760
+ const stored = loadCredentialsSafely(config2);
101761
+ const [[latestVersion, oldestSupportedVersion], serviceRead] = await Promise.all([
101762
+ fetchVersionFacts(config2.appEnv, stored.credentials, CLI_PACKAGE_NAME),
101763
+ service
101764
+ ]);
101765
+ return { stored, latestVersion, oldestSupportedVersion, serviceRead };
101766
+ });
101597
101767
  console.log(
101598
101768
  renderDoctorReport({
101599
101769
  config: config2,
101600
101770
  cliVersion: CLI_VERSION,
101601
- latestVersion,
101602
- oldestSupportedVersion,
101771
+ latestVersion: found.latestVersion,
101772
+ oldestSupportedVersion: found.oldestSupportedVersion,
101603
101773
  nodeVersion: process.version,
101604
101774
  platform: `${process.platform} ${process.arch}`,
101605
101775
  install: inspectThisInstall(config2),
101606
- ...stored,
101607
- ...readServiceSafely(config2),
101776
+ ...found.stored,
101777
+ ...found.serviceRead,
101608
101778
  ...readCredentialStoreSafely(config2),
101609
101779
  daemon: describeDaemonState(readCollectorStatus(config2.appEnv)),
101610
101780
  control: readCollectorControl(config2.appEnv),
@@ -101913,9 +102083,15 @@ function readServiceSafely(config2) {
101913
102083
  try {
101914
102084
  return { service: serviceState2(config2) };
101915
102085
  } catch (error63) {
101916
- return { service: "unavailable", serviceError: error63 instanceof Error ? error63.message : "Could not read background sync status" };
102086
+ return unreadService(error63);
101917
102087
  }
101918
102088
  }
102089
+ function readServiceSafelyAsync(config2) {
102090
+ return serviceStateAsync(config2).then((service) => ({ service }), unreadService);
102091
+ }
102092
+ function unreadService(error63) {
102093
+ return { service: "unavailable", serviceError: error63 instanceof Error ? error63.message : "Could not read background sync status" };
102094
+ }
101919
102095
  function readCredentialStoreSafely(config2) {
101920
102096
  const migration = describeCredentialMigration(config2.appEnv);
101921
102097
  const facts = migration === null ? {} : { credentialMigration: migration };
@@ -102181,6 +102357,29 @@ function entryPath() {
102181
102357
  }
102182
102358
  }
102183
102359
  var cliCommand = "none";
102360
+ var CLI_COMMANDS = /* @__PURE__ */ new Set([
102361
+ "init",
102362
+ "connect",
102363
+ "disconnect",
102364
+ "enroll",
102365
+ "status",
102366
+ "doctor",
102367
+ "menu",
102368
+ "report-agent-click",
102369
+ "dismiss-codex-hook-warning",
102370
+ "dismiss-mcp-warning",
102371
+ "workspace",
102372
+ "resume-session",
102373
+ "update",
102374
+ "restart",
102375
+ "pause",
102376
+ "resume",
102377
+ "sync",
102378
+ "folders",
102379
+ "watch",
102380
+ "uninstall",
102381
+ "install-release"
102382
+ ]);
102184
102383
  var MENU_QUIET_COMMANDS = /* @__PURE__ */ new Set(["menu", "watch", "report-agent-click", "status", "doctor", "none", "help"]);
102185
102384
  async function wakeMenus() {
102186
102385
  if (MENU_QUIET_COMMANDS.has(cliCommand)) return;
@@ -102213,4 +102412,4 @@ undici/lib/web/websocket/frame.js:
102213
102412
  (*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> *)
102214
102413
  */
102215
102414
 
102216
- //# debugId=c205f968-8b28-5dc5-9420-5b3fae8d2c6f
102415
+ //# debugId=d3cdc2c4-688f-5244-bc1d-b1fd4151981c
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usepowerplant/cli",
3
- "version": "0.4.27",
3
+ "version": "0.4.28",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },