counterparts 0.3.38 → 0.3.39
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/CHANGELOG.md +30 -0
- package/README.md +2 -1
- package/docs/QUICKSTART.md +2 -1
- package/package.json +9 -1
- package/src/adapters/claude-code/NOTES.md +44 -0
- package/src/adapters/claude-code/bin/runner.ts +62 -2
- package/src/adapters/claude-code/doctor.ts +127 -2
- package/src/adapters/claude-code/hooks.ts +66 -1
- package/src/adapters/cli/commands.ts +1 -1
- package/src/adapters/cli/ui.ts +10 -0
- package/src/adapters/cli/wire.ts +11 -5
- package/src/adapters/config.ts +23 -0
- package/src/adapters/expansions.ts +4 -3
- package/src/adapters/mcp/NOTES.md +2 -0
- package/src/adapters/mcp/bin/serve.ts +31 -2
- package/src/adapters/mcp/server-words.ts +1 -1
- package/src/adapters/mcp/server.ts +59 -0
- package/src/adapters/mcp/tools.ts +35 -3
- package/src/adapters/sessions.ts +28 -0
- package/src/adapters/update-check.ts +870 -0
- package/src/adapters/update-words.ts +25 -5
- package/tools/install-loop/run.sh +3 -0
|
@@ -0,0 +1,870 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE DAILY UPDATE CHECK AND ITS LINES (U1b, 2026-10-28). Design:
|
|
3
|
+
* `~/counterparts-notes/2026-10-27-briefs/U1-design-note.md` rev 2, with
|
|
4
|
+
* Mike's answers (10-27 20:42) over it where they differ.
|
|
5
|
+
*
|
|
6
|
+
* A leaf beside `update-words.ts`, because three adapters use it and adapters
|
|
7
|
+
* never import each other: the detached worker makes the request
|
|
8
|
+
* (`claude-code/bin/runner.ts`, after its store is closed), the session-start
|
|
9
|
+
* wake and Desktop's `wake` say the lines (`claude-code/hooks.ts`,
|
|
10
|
+
* `mcp/bin/serve.ts`), the MCP `scope` tool takes "stop reminding me about
|
|
11
|
+
* updates" (`mcp/server.ts`), and doctor reports it all.
|
|
12
|
+
*
|
|
13
|
+
* **The request.** One `GET https://registry.npmjs.org/counterparts/latest`,
|
|
14
|
+
* at most once a day, failures included (a failed day tries again the next). No
|
|
15
|
+
* query, no cookie kept, no id, not even the installed version; the
|
|
16
|
+
* User-Agent is the constant `counterparts`, and no `Accept` header asks for
|
|
17
|
+
* npm's abbreviated document (which drops the release flags). It never runs
|
|
18
|
+
* in a hook, so it can never hold a session up. The body is read as a stream
|
|
19
|
+
* and cut at 16 KB; redirects are refused; 3 s is the limit. Only VALIDATED
|
|
20
|
+
* SCALARS are copied out — version strings matching `x.y.z`, an integer, a
|
|
21
|
+
* boolean — and every line is built from local templates, so no text from
|
|
22
|
+
* the response can ever reach a model.
|
|
23
|
+
*
|
|
24
|
+
* **The switches** (the names /privacy publishes; change both together):
|
|
25
|
+
* - `"updateCheck": false` in `claude-code.json` — the durable one;
|
|
26
|
+
* - telling your Claude to stop: the `scope` tool's `updates: "off"`,
|
|
27
|
+
* recorded in the store (`UPDATE_OFF_KEY`), which every process here
|
|
28
|
+
* reads — the worker, the hook, Desktop's server and doctor;
|
|
29
|
+
* - `COUNTERPARTS_UPDATE_CHECK=off` where Counterparts runs;
|
|
30
|
+
* - Claude Code's `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`.
|
|
31
|
+
* Any of them: no request. The first three are the person saying "no", so no
|
|
32
|
+
* wake says anything about updates either (Mike's must-have, Q4: "stop
|
|
33
|
+
* reminding me" must be enough). Only the last — which asked for no traffic,
|
|
34
|
+
* not for silence — keeps the local "a newer one may be out" line.
|
|
35
|
+
*
|
|
36
|
+
* **Once-ness.** What has been told lives in one store meta key
|
|
37
|
+
* (`UPDATE_TOLD_KEY`), claimed with `Store.updateMeta` the way
|
|
38
|
+
* `stale-windows.ts` claims its line: two windows starting together say it
|
|
39
|
+
* once, and a told line writes nothing.
|
|
40
|
+
*/
|
|
41
|
+
import { closeSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
|
|
42
|
+
import { dirname, join, relative, resolve, isAbsolute } from "node:path";
|
|
43
|
+
|
|
44
|
+
import { lastOffer, offerDue } from "../core/onboarding.js";
|
|
45
|
+
import { shortDay, yearOf } from "../core/time.js";
|
|
46
|
+
import type { Store } from "../core/store/index.js";
|
|
47
|
+
import type { AdapterConfig } from "./config.js";
|
|
48
|
+
import { sidebarPluginRecorded } from "./host-wiring.js";
|
|
49
|
+
import type { InstallRoute } from "./plugin.js";
|
|
50
|
+
import { PLUGIN_ROOT_ENV, recordedForThisCopy } from "./plugin.js";
|
|
51
|
+
import { TRANSPILED } from "./runtime.js";
|
|
52
|
+
import type { RuntimeKind } from "./runtime.js";
|
|
53
|
+
import { installedVersion } from "./sessions.js";
|
|
54
|
+
import { PLUGIN_UPDATE_COMMUNITY, PLUGIN_UPDATE_STEP, PLUGIN_UPDATE_SYNCED, npmUpdateCommand, reloadStep } from "./update-words.js";
|
|
55
|
+
|
|
56
|
+
// ── names ─────────────────────────────────────────────────────────────────
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* THE DAY THIS VERSION WAS RELEASED, `YYYY-MM-DD` — moved with
|
|
60
|
+
* `SERVER_VERSION` (`mcp/server-words.ts`) in the release commit
|
|
61
|
+
* (docs/RELEASING.md §1). A copy that makes no check (the directory flavor,
|
|
62
|
+
* Claude Code's no-traffic switch, a check failing for weeks) says it is over
|
|
63
|
+
* 30 days old from this alone, with nothing fetched. `test/update-check.test.ts`
|
|
64
|
+
* holds it to CHANGELOG's heading for `SERVER_VERSION` once there is one.
|
|
65
|
+
*/
|
|
66
|
+
export const RELEASE_DATE = "2026-10-28";
|
|
67
|
+
|
|
68
|
+
export const UPDATE_CHECK_ENV = "COUNTERPARTS_UPDATE_CHECK";
|
|
69
|
+
export const NONESSENTIAL_TRAFFIC_ENV = "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC";
|
|
70
|
+
/** Claude Code's switches that hide the plugin manager's Enable auto-update toggle (loading.md). */
|
|
71
|
+
export const HIDES_AUTO_UPDATE_ENV: readonly string[] = [NONESSENTIAL_TRAFFIC_ENV, "DISABLE_UPDATES", "DISABLE_AUTOUPDATER"];
|
|
72
|
+
export const FORCE_AUTO_UPDATE_ENV = "FORCE_AUTOUPDATE_PLUGINS";
|
|
73
|
+
|
|
74
|
+
export const LATEST_URL = "https://registry.npmjs.org/counterparts/latest";
|
|
75
|
+
export const UPDATE_CHECK_TIMEOUT_MS = 3_000;
|
|
76
|
+
export const LATEST_BODY_CAP = 16 * 1024;
|
|
77
|
+
|
|
78
|
+
/** The worker's record, beside the configuration (`npm-live.json`'s neighbour). */
|
|
79
|
+
export const UPDATES_FILE = "updates.json";
|
|
80
|
+
/** The day's try latches. */
|
|
81
|
+
export const UPDATES_DIR = "updates";
|
|
82
|
+
const STATE_CAP = 16 * 1024;
|
|
83
|
+
|
|
84
|
+
/** `"off"` when the person told their Claude to stop (the `scope` tool's `updates`). */
|
|
85
|
+
export const UPDATE_OFF_KEY = "adapter.update.check";
|
|
86
|
+
/** What the wake has said, as JSON (`Told`). */
|
|
87
|
+
export const UPDATE_TOLD_KEY = "adapter.update.told";
|
|
88
|
+
|
|
89
|
+
/** The behind rule's N when the release says none. */
|
|
90
|
+
export const DEFAULT_TELL_BEHIND = 3;
|
|
91
|
+
/** A behind line is said again after this many days, if the gap has not grown by N first. */
|
|
92
|
+
export const RETELL_DAYS = 14;
|
|
93
|
+
/** An urgent line is said once a day on at most this many days. */
|
|
94
|
+
export const URGENT_DAYS = 3;
|
|
95
|
+
/** The age line: a copy older than this many days, said once per copy. */
|
|
96
|
+
export const AGE_DAYS = 30;
|
|
97
|
+
/** A check that has not succeeded for this many days counts as "no check" for the age line. */
|
|
98
|
+
export const FAILING_DAYS = 14;
|
|
99
|
+
|
|
100
|
+
/** W1's lead (`claude-code/doctor-meaning.ts#MEANING_OFF_LEAD`), the same words: one voice for maintenance lines. */
|
|
101
|
+
export const UPDATE_LEAD = "Counterparts — tell your person when it fits, once this session:";
|
|
102
|
+
/** The urgent line's lead: now, not "when it fits". */
|
|
103
|
+
export const UPDATE_URGENT_LEAD = "Counterparts — tell your person now:";
|
|
104
|
+
/**
|
|
105
|
+
* Room an update line leaves under the host's ceiling for what may follow it
|
|
106
|
+
* in the same envelope (the write-up pointer, the first-launch question): a
|
|
107
|
+
* line that would eat into it is not composed, and waits for a wake with room.
|
|
108
|
+
*/
|
|
109
|
+
export const UPDATE_ROOM_MARGIN = 600;
|
|
110
|
+
/** For the model, after every non-urgent update line: how "stop reminding me" is done. */
|
|
111
|
+
export const STOP_HINT = 'If they say stop: scope updates "off".';
|
|
112
|
+
|
|
113
|
+
// ── the switch ────────────────────────────────────────────────────────────
|
|
114
|
+
|
|
115
|
+
/** Which switch is off, or `none`. `asked` is the person telling their Claude. */
|
|
116
|
+
export type UpdateSwitch = "config" | "asked" | "env" | "nonessential" | "none";
|
|
117
|
+
|
|
118
|
+
const OFF_WORDS = new Set(["off", "0", "false", "no", "disable", "disabled"]);
|
|
119
|
+
|
|
120
|
+
/** A Claude Code style boolean variable: set to anything but empty, `0` or `false`. Off is the safe direction. */
|
|
121
|
+
export function envSet(value: string | undefined): boolean {
|
|
122
|
+
if (value === undefined) return false;
|
|
123
|
+
const v = value.trim().toLowerCase();
|
|
124
|
+
return v.length > 0 && v !== "0" && v !== "false";
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Did the person tell their Claude to stop? Never throws. An unreadable store
|
|
129
|
+
* reads as "no" for a line (saying nothing is the quiet direction anyway) and
|
|
130
|
+
* as "yes" for the worker, which would otherwise make a request the person may
|
|
131
|
+
* have refused (`failClosed`).
|
|
132
|
+
*/
|
|
133
|
+
export function askedOff(store: Pick<Store, "getMeta"> | null, opts: { readonly failClosed?: boolean } = {}): boolean {
|
|
134
|
+
try {
|
|
135
|
+
return store?.getMeta(UPDATE_OFF_KEY) === "off";
|
|
136
|
+
} catch {
|
|
137
|
+
return opts.failClosed === true;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function updateSwitch(input: {
|
|
142
|
+
readonly config: Pick<AdapterConfig, "updateCheck">;
|
|
143
|
+
readonly asked: boolean;
|
|
144
|
+
readonly env: Record<string, string | undefined>;
|
|
145
|
+
}): UpdateSwitch {
|
|
146
|
+
if (input.config.updateCheck === false) return "config";
|
|
147
|
+
if (input.asked) return "asked";
|
|
148
|
+
const own = input.env[UPDATE_CHECK_ENV];
|
|
149
|
+
if (own !== undefined && OFF_WORDS.has(own.trim().toLowerCase())) return "env";
|
|
150
|
+
if (envSet(input.env[NONESSENTIAL_TRAFFIC_ENV])) return "nonessential";
|
|
151
|
+
return "none";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The person said no (any switch but Claude Code's traffic one): silence, the age line included. */
|
|
155
|
+
export function personSaidNo(sw: UpdateSwitch): boolean {
|
|
156
|
+
return sw === "config" || sw === "asked" || sw === "env";
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ── versions ──────────────────────────────────────────────────────────────
|
|
160
|
+
|
|
161
|
+
const PLAIN = /^\d{1,4}\.\d{1,4}\.\d{1,6}$/;
|
|
162
|
+
const PRERELEASE = /^\d{1,4}\.\d{1,4}\.\d{1,6}-[0-9A-Za-z.-]{1,40}$/;
|
|
163
|
+
|
|
164
|
+
function parts(v: string): [number, number, number] | null {
|
|
165
|
+
const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v.trim());
|
|
166
|
+
return m === null ? null : [Number(m[1]), Number(m[2]), Number(m[3])];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** `a` below `b`, comparing `x.y.z` only (a `-<sha>` suffix ignored); false when either is not a version. */
|
|
170
|
+
export function versionBelow(a: string | null, b: string | null): boolean {
|
|
171
|
+
if (a === null || b === null) return false;
|
|
172
|
+
const x = parts(a);
|
|
173
|
+
const y = parts(b);
|
|
174
|
+
if (x === null || y === null) return false;
|
|
175
|
+
for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i]! < y[i]!;
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** How far behind: patch releases within one minor; a different major or minor counts as far (1000). */
|
|
180
|
+
export function releasesBehind(installed: string, latest: string): number {
|
|
181
|
+
const x = parts(installed);
|
|
182
|
+
const y = parts(latest);
|
|
183
|
+
if (x === null || y === null || !versionBelow(installed, latest)) return 0;
|
|
184
|
+
if (x[0] !== y[0] || x[1] !== y[1]) return 1000;
|
|
185
|
+
return y[2] - x[2];
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ── the request ───────────────────────────────────────────────────────────
|
|
189
|
+
|
|
190
|
+
/** What a release says about who should hear of it (`package.json` `"counterparts": { "updates": … }`). */
|
|
191
|
+
export interface ReleaseFlags {
|
|
192
|
+
/** Anyone below it is told once. Cumulative: only ever raised. */
|
|
193
|
+
readonly tellBelow: string | null;
|
|
194
|
+
/** Anyone below it is told urgently. Cumulative too. */
|
|
195
|
+
readonly urgentBelow: string | null;
|
|
196
|
+
/** N for the behind rule. */
|
|
197
|
+
readonly tellBehind: number;
|
|
198
|
+
/** False for a release whose plugin pin is not moving: plugin installs are not told about it. */
|
|
199
|
+
readonly plugin: boolean;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export type LatestRead =
|
|
203
|
+
| ({ readonly ok: true; readonly latest: string | null } & ReleaseFlags)
|
|
204
|
+
| { readonly ok: false; readonly code: string };
|
|
205
|
+
|
|
206
|
+
/** Validate `/latest`'s JSON into scalars. Pure. Anything carrying text where a version belongs is a failure. */
|
|
207
|
+
export function readLatest(body: unknown): LatestRead {
|
|
208
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) return { ok: false, code: "bad-json" };
|
|
209
|
+
const rec = body as Record<string, unknown>;
|
|
210
|
+
const version = rec["version"];
|
|
211
|
+
if (typeof version !== "string") return { ok: false, code: "bad-version" };
|
|
212
|
+
let latest: string | null;
|
|
213
|
+
if (PLAIN.test(version)) latest = version;
|
|
214
|
+
// A prerelease published without `--tag`: no news, not a fault.
|
|
215
|
+
else if (PRERELEASE.test(version)) latest = null;
|
|
216
|
+
else return { ok: false, code: "bad-version" };
|
|
217
|
+
const block = (rec["counterparts"] as Record<string, unknown> | undefined)?.["updates"];
|
|
218
|
+
const flags = block === undefined ? {} : block;
|
|
219
|
+
if (flags === null || typeof flags !== "object" || Array.isArray(flags)) return { ok: false, code: "bad-flags" };
|
|
220
|
+
const f = flags as Record<string, unknown>;
|
|
221
|
+
const floor = (key: string): string | null | false => {
|
|
222
|
+
const v = f[key];
|
|
223
|
+
if (v === undefined || v === null) return null;
|
|
224
|
+
return typeof v === "string" && PLAIN.test(v) ? v : false;
|
|
225
|
+
};
|
|
226
|
+
const tellBelow = floor("tellBelow");
|
|
227
|
+
const urgentBelow = floor("urgentBelow");
|
|
228
|
+
if (tellBelow === false || urgentBelow === false) return { ok: false, code: "bad-flags" };
|
|
229
|
+
const n = f["tellBehind"];
|
|
230
|
+
if (n !== undefined && (typeof n !== "number" || !Number.isInteger(n))) return { ok: false, code: "bad-flags" };
|
|
231
|
+
const p = f["plugin"];
|
|
232
|
+
if (p !== undefined && typeof p !== "boolean") return { ok: false, code: "bad-flags" };
|
|
233
|
+
return {
|
|
234
|
+
ok: true,
|
|
235
|
+
latest,
|
|
236
|
+
tellBelow,
|
|
237
|
+
urgentBelow,
|
|
238
|
+
tellBehind: n === undefined ? DEFAULT_TELL_BEHIND : Math.min(50, Math.max(1, n)),
|
|
239
|
+
plugin: p !== false,
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* THE ONE REQUEST. Never throws: every failure is `{ ok: false, code }`.
|
|
247
|
+
* The fetch is injected (the worker passes the runtime's own); tests pass a
|
|
248
|
+
* stub, and nothing here reaches for a global.
|
|
249
|
+
*/
|
|
250
|
+
export async function fetchLatest(input: { readonly fetch: FetchLike; readonly signal?: AbortSignal; readonly timeoutMs?: number }): Promise<LatestRead> {
|
|
251
|
+
// A timer of our own, not `AbortSignal.timeout`: Node unrefs that one, so a
|
|
252
|
+
// request that holds nothing else open would let the loop drain before the
|
|
253
|
+
// limit ever fired. Cleared in `finally`, so it never outlives the request.
|
|
254
|
+
const limit = new AbortController();
|
|
255
|
+
const timer = setTimeout(() => limit.abort(), input.timeoutMs ?? UPDATE_CHECK_TIMEOUT_MS);
|
|
256
|
+
const signal = input.signal === undefined ? limit.signal : AbortSignal.any([limit.signal, input.signal]);
|
|
257
|
+
try {
|
|
258
|
+
const res = await input.fetch(LATEST_URL, {
|
|
259
|
+
method: "GET",
|
|
260
|
+
redirect: "error",
|
|
261
|
+
signal,
|
|
262
|
+
headers: { "user-agent": "counterparts" },
|
|
263
|
+
});
|
|
264
|
+
if (!res.ok) return { ok: false, code: `http-${String(res.status)}` };
|
|
265
|
+
if (res.body === null) return { ok: false, code: "no-body" };
|
|
266
|
+
const reader = res.body.getReader();
|
|
267
|
+
const chunks: Uint8Array[] = [];
|
|
268
|
+
let bytes = 0;
|
|
269
|
+
for (;;) {
|
|
270
|
+
const { done, value } = await reader.read();
|
|
271
|
+
if (done) break;
|
|
272
|
+
bytes += value.byteLength;
|
|
273
|
+
if (bytes > LATEST_BODY_CAP) {
|
|
274
|
+
await reader.cancel().catch(() => undefined);
|
|
275
|
+
return { ok: false, code: "too-large" };
|
|
276
|
+
}
|
|
277
|
+
chunks.push(value);
|
|
278
|
+
}
|
|
279
|
+
const all = new Uint8Array(bytes);
|
|
280
|
+
let at = 0;
|
|
281
|
+
for (const c of chunks) {
|
|
282
|
+
all.set(c, at);
|
|
283
|
+
at += c.byteLength;
|
|
284
|
+
}
|
|
285
|
+
let parsed: unknown;
|
|
286
|
+
try {
|
|
287
|
+
parsed = JSON.parse(new TextDecoder().decode(all));
|
|
288
|
+
} catch {
|
|
289
|
+
return { ok: false, code: "bad-json" };
|
|
290
|
+
}
|
|
291
|
+
return readLatest(parsed);
|
|
292
|
+
} catch (err) {
|
|
293
|
+
if (signal.aborted) return { ok: false, code: "timeout" };
|
|
294
|
+
return { ok: false, code: err instanceof Error && err.name.length > 0 ? err.name.slice(0, 40) : "unreachable" };
|
|
295
|
+
} finally {
|
|
296
|
+
clearTimeout(timer);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ── the worker's record ───────────────────────────────────────────────────
|
|
301
|
+
|
|
302
|
+
/** `updates.json`: what the worker last decided and learned. Validated on every read. */
|
|
303
|
+
export interface UpdateState {
|
|
304
|
+
/** The switch the worker last obeyed (doctor reports this, not its own environment). */
|
|
305
|
+
readonly switch: UpdateSwitch;
|
|
306
|
+
readonly at: string;
|
|
307
|
+
/** Claude Code keeps this plugin updated itself: no check made. */
|
|
308
|
+
readonly autoUpdate?: boolean;
|
|
309
|
+
/** The date of the last successful check, and when. */
|
|
310
|
+
readonly checkedDate?: string;
|
|
311
|
+
readonly okAt?: string;
|
|
312
|
+
readonly failedAt?: string;
|
|
313
|
+
readonly failCode?: string;
|
|
314
|
+
/** The first date of the failures since the last success; absent after a success. */
|
|
315
|
+
readonly failingSince?: string;
|
|
316
|
+
/** Failed days in a row since the last success (one try a day). */
|
|
317
|
+
readonly failures?: number;
|
|
318
|
+
/** The newest plain `x.y.z` npm reported, or null (a prerelease `latest`: no news). */
|
|
319
|
+
readonly latest?: string | null;
|
|
320
|
+
/** The date `latest` was first seen: a plugin install is told only from the next day on. */
|
|
321
|
+
readonly latestSeen?: string;
|
|
322
|
+
readonly flags?: ReleaseFlags;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
export function updatesPath(configPath: string): string {
|
|
326
|
+
return join(dirname(configPath), UPDATES_FILE);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const SWITCHES: readonly UpdateSwitch[] = ["config", "asked", "env", "nonessential", "none"];
|
|
330
|
+
const DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
331
|
+
const ISO = /^\d{4}-\d{2}-\d{2}T[0-9:.]+Z$/;
|
|
332
|
+
const CODE = /^[A-Za-z0-9_.-]{1,40}$/;
|
|
333
|
+
|
|
334
|
+
/** Read `updates.json`, size-bounded; anything malformed is no record at all. Never throws. */
|
|
335
|
+
export function readUpdateState(configPath: string): UpdateState | null {
|
|
336
|
+
try {
|
|
337
|
+
const file = updatesPath(configPath);
|
|
338
|
+
if (statSync(file).size > STATE_CAP) return null;
|
|
339
|
+
const raw: unknown = JSON.parse(readFileSync(file, "utf8"));
|
|
340
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
|
|
341
|
+
const r = raw as Record<string, unknown>;
|
|
342
|
+
if (typeof r["switch"] !== "string" || !(SWITCHES as readonly string[]).includes(r["switch"])) return null;
|
|
343
|
+
if (typeof r["at"] !== "string" || !ISO.test(r["at"])) return null;
|
|
344
|
+
const out: { -readonly [K in keyof UpdateState]: UpdateState[K] } = { switch: r["switch"] as UpdateSwitch, at: r["at"] };
|
|
345
|
+
if (r["autoUpdate"] === true) out.autoUpdate = true;
|
|
346
|
+
if (typeof r["checkedDate"] === "string" && DATE.test(r["checkedDate"])) out.checkedDate = r["checkedDate"];
|
|
347
|
+
if (typeof r["okAt"] === "string" && ISO.test(r["okAt"])) out.okAt = r["okAt"];
|
|
348
|
+
if (typeof r["failedAt"] === "string" && ISO.test(r["failedAt"])) out.failedAt = r["failedAt"];
|
|
349
|
+
if (typeof r["failCode"] === "string" && CODE.test(r["failCode"])) out.failCode = r["failCode"];
|
|
350
|
+
if (typeof r["failingSince"] === "string" && DATE.test(r["failingSince"])) out.failingSince = r["failingSince"];
|
|
351
|
+
if (typeof r["failures"] === "number" && Number.isInteger(r["failures"]) && r["failures"] > 0 && r["failures"] < 100_000) out.failures = r["failures"];
|
|
352
|
+
if (r["latest"] === null || (typeof r["latest"] === "string" && PLAIN.test(r["latest"]))) out.latest = r["latest"];
|
|
353
|
+
if (typeof r["latestSeen"] === "string" && DATE.test(r["latestSeen"])) out.latestSeen = r["latestSeen"];
|
|
354
|
+
if (r["flags"] !== undefined) {
|
|
355
|
+
// The same validation as the response's, so a hand-edited file says nothing either.
|
|
356
|
+
const f = readLatest({ version: "0.0.0", counterparts: { updates: r["flags"] } });
|
|
357
|
+
if (f.ok) out.flags = { tellBelow: f.tellBelow, urgentBelow: f.urgentBelow, tellBehind: f.tellBehind, plugin: f.plugin };
|
|
358
|
+
}
|
|
359
|
+
return out;
|
|
360
|
+
} catch {
|
|
361
|
+
return null;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function writeUpdateState(configPath: string, state: UpdateState): boolean {
|
|
366
|
+
const file = updatesPath(configPath);
|
|
367
|
+
const tmp = `${file}.${String(process.pid)}.tmp`;
|
|
368
|
+
try {
|
|
369
|
+
writeFileSync(tmp, `${JSON.stringify(state)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
370
|
+
try {
|
|
371
|
+
chmodSync(tmp, 0o600);
|
|
372
|
+
} catch {
|
|
373
|
+
// a filesystem without modes: the write stands
|
|
374
|
+
}
|
|
375
|
+
renameSync(tmp, file);
|
|
376
|
+
return true;
|
|
377
|
+
} catch {
|
|
378
|
+
rmSync(tmp, { force: true });
|
|
379
|
+
return false;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// ── where this copy came from (read off its own path) ─────────────────────
|
|
384
|
+
|
|
385
|
+
/** `counterparts` (ours), `claude-community` (the directory listing), `synced` (claude.ai's directory), or null. */
|
|
386
|
+
export type PluginMarket = string | "synced" | null;
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* The marketplace a plugin copy came through, read off `CLAUDE_PLUGIN_ROOT`
|
|
390
|
+
* only — `<plugins>/cache/<marketplace>/<plugin>/<version>` or
|
|
391
|
+
* `<plugins>/synced/…`. Reads no file, so the directory flavor (which reads
|
|
392
|
+
* nothing of Claude Code's) may ask it too. Null outside the plugins folder.
|
|
393
|
+
*/
|
|
394
|
+
export function pluginMarket(input: { readonly home: string; readonly env: Record<string, string | undefined> }): PluginMarket {
|
|
395
|
+
const root = (input.env[PLUGIN_ROOT_ENV] ?? "").trim();
|
|
396
|
+
if (root.length === 0) return null;
|
|
397
|
+
const moved = (input.env["CLAUDE_CONFIG_DIR"] ?? "").trim();
|
|
398
|
+
const cache = (input.env["CLAUDE_CODE_PLUGIN_CACHE_DIR"] ?? "").trim();
|
|
399
|
+
const plugins = resolve(cache.length > 0 ? cache : join(moved.length > 0 ? moved : join(input.home, ".claude"), "plugins"));
|
|
400
|
+
const rel = relative(plugins, resolve(root));
|
|
401
|
+
if (rel.length === 0 || rel.startsWith("..") || isAbsolute(rel)) return null;
|
|
402
|
+
const seg = rel.split(/[\\/]/);
|
|
403
|
+
if (seg[0] === "synced") return "synced";
|
|
404
|
+
if (seg[0] === "cache" && (seg[1] ?? "").length > 0) return seg[1] ?? null;
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function readJson(path: string): Record<string, unknown> | null {
|
|
409
|
+
try {
|
|
410
|
+
if (statSync(path).size > 256 * 1024) return null;
|
|
411
|
+
const v: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
412
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
|
|
413
|
+
} catch {
|
|
414
|
+
return null;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* IS CLAUDE CODE'S OWN AUTO-UPDATE ON for this marketplace? (Full flavor only;
|
|
420
|
+
* READ-ONLY.) Settings `extraKnownMarketplaces.<mkt>.autoUpdate` first, then
|
|
421
|
+
* `known_marketplaces.json`'s `<mkt>.autoUpdate`; neither saying: off, the
|
|
422
|
+
* default for a third-party marketplace. Never throws.
|
|
423
|
+
*/
|
|
424
|
+
export function claudeAutoUpdate(input: { readonly home: string; readonly env: Record<string, string | undefined>; readonly market: string }): boolean {
|
|
425
|
+
try {
|
|
426
|
+
const moved = (input.env["CLAUDE_CONFIG_DIR"] ?? "").trim();
|
|
427
|
+
const configDir = moved.length > 0 ? moved : join(input.home, ".claude");
|
|
428
|
+
const extra = readJson(join(configDir, "settings.json"))?.["extraKnownMarketplaces"];
|
|
429
|
+
const fromSettings = (extra as Record<string, Record<string, unknown>> | undefined)?.[input.market]?.["autoUpdate"];
|
|
430
|
+
if (typeof fromSettings === "boolean") return fromSettings;
|
|
431
|
+
const cache = (input.env["CLAUDE_CODE_PLUGIN_CACHE_DIR"] ?? "").trim();
|
|
432
|
+
const known = readJson(join(cache.length > 0 ? cache : join(configDir, "plugins"), "known_marketplaces.json"));
|
|
433
|
+
const fromKnown = (known?.[input.market] as Record<string, unknown> | undefined)?.["autoUpdate"];
|
|
434
|
+
return fromKnown === true;
|
|
435
|
+
} catch {
|
|
436
|
+
return false;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** Claude Code hides the Enable auto-update toggle: offering it would point at a menu item that is not there. */
|
|
441
|
+
export function autoUpdateHidden(env: Record<string, string | undefined>): boolean {
|
|
442
|
+
if (envSet(env[FORCE_AUTO_UPDATE_ENV])) return false;
|
|
443
|
+
return HIDES_AUTO_UPDATE_ENV.some((k) => envSet(env[k]));
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// ── the worker's step ─────────────────────────────────────────────────────
|
|
447
|
+
|
|
448
|
+
export interface UpdateCheckReport {
|
|
449
|
+
readonly ran: boolean;
|
|
450
|
+
readonly reason: "observer" | "off" | "auto-update" | "checked-today" | "aborted" | "ok" | "failed";
|
|
451
|
+
readonly switch: UpdateSwitch;
|
|
452
|
+
readonly code?: string;
|
|
453
|
+
readonly latest?: string | null;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* ONE WORKER'S TURN AT THE CHECK. Runs after the worker's store is closed
|
|
459
|
+
* (it needs none: `asked` was read before the close). Never throws.
|
|
460
|
+
*
|
|
461
|
+
* - observer: nothing, not even a record;
|
|
462
|
+
* - any switch off: no request; the switch is recorded so doctor can say
|
|
463
|
+
* which (doctor in a terminal does not share the worker's environment);
|
|
464
|
+
* - Claude Code keeps this plugin updated (`autoUpdate`): no request;
|
|
465
|
+
* - a worker already stopping (its watchdog fired): nothing, no try spent;
|
|
466
|
+
* - otherwise AT MOST ONE REQUEST A DAY, failures included (/privacy says
|
|
467
|
+
* "once a day"): the day's try is claimed with an exclusive latch file,
|
|
468
|
+
* so two workers starting together make one request, and a day that
|
|
469
|
+
* failed simply tries again the next day.
|
|
470
|
+
*/
|
|
471
|
+
export async function runUpdateCheck(input: {
|
|
472
|
+
readonly configPath: string;
|
|
473
|
+
readonly config: AdapterConfig;
|
|
474
|
+
readonly asked: boolean;
|
|
475
|
+
readonly env: Record<string, string | undefined>;
|
|
476
|
+
readonly date: string;
|
|
477
|
+
readonly fetch: FetchLike;
|
|
478
|
+
readonly signal?: AbortSignal;
|
|
479
|
+
readonly now?: number;
|
|
480
|
+
readonly autoUpdate?: boolean;
|
|
481
|
+
}): Promise<UpdateCheckReport> {
|
|
482
|
+
const sw = updateSwitch({ config: input.config, asked: input.asked, env: input.env });
|
|
483
|
+
if (input.config.observer === true) return { ran: false, reason: "observer", switch: sw };
|
|
484
|
+
const now = input.now ?? Date.now();
|
|
485
|
+
const at = new Date(now).toISOString();
|
|
486
|
+
try {
|
|
487
|
+
const prev = readUpdateState(input.configPath);
|
|
488
|
+
if (sw !== "none") {
|
|
489
|
+
if (prev?.switch !== sw) writeUpdateState(input.configPath, { ...(prev ?? {}), switch: sw, at });
|
|
490
|
+
return { ran: false, reason: "off", switch: sw };
|
|
491
|
+
}
|
|
492
|
+
if (input.autoUpdate === true) {
|
|
493
|
+
if (prev?.autoUpdate !== true || prev.switch !== "none") writeUpdateState(input.configPath, { ...(prev ?? {}), switch: "none", at, autoUpdate: true });
|
|
494
|
+
return { ran: false, reason: "auto-update", switch: sw };
|
|
495
|
+
}
|
|
496
|
+
if (input.signal?.aborted === true) return { ran: false, reason: "aborted", switch: sw };
|
|
497
|
+
// The day's one try: its latch, every other day's swept.
|
|
498
|
+
const dir = join(dirname(input.configPath), UPDATES_DIR);
|
|
499
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
500
|
+
for (const name of readdirSync(dir)) {
|
|
501
|
+
const m = /^try-(\d{4}-\d{2}-\d{2})(?:-\d+)?$/.exec(name);
|
|
502
|
+
if (m !== null && m[1] !== input.date) rmSync(join(dir, name), { force: true });
|
|
503
|
+
}
|
|
504
|
+
try {
|
|
505
|
+
closeSync(openSync(join(dir, `try-${input.date}`), "wx", 0o600));
|
|
506
|
+
} catch {
|
|
507
|
+
// Today's try is taken — made, failed, or in flight in another worker.
|
|
508
|
+
if (prev !== null && (prev.switch !== "none" || prev.autoUpdate === true)) {
|
|
509
|
+
const { autoUpdate: _drop, ...rest } = prev;
|
|
510
|
+
writeUpdateState(input.configPath, { ...rest, switch: "none", at });
|
|
511
|
+
}
|
|
512
|
+
return { ran: false, reason: "checked-today", switch: sw };
|
|
513
|
+
}
|
|
514
|
+
const read = await fetchLatest({ fetch: input.fetch, ...(input.signal === undefined ? {} : { signal: input.signal }) });
|
|
515
|
+
const latestPrev = readUpdateState(input.configPath) ?? prev;
|
|
516
|
+
if (!read.ok) {
|
|
517
|
+
const { autoUpdate: _drop, ...rest } = latestPrev ?? { switch: "none" as const, at };
|
|
518
|
+
writeUpdateState(input.configPath, {
|
|
519
|
+
...rest,
|
|
520
|
+
switch: "none",
|
|
521
|
+
at,
|
|
522
|
+
failedAt: at,
|
|
523
|
+
failCode: read.code,
|
|
524
|
+
// Failed days in a row (one try a day), and the first of them: doctor
|
|
525
|
+
// turns amber, and the age line counts this copy as unchecked, only
|
|
526
|
+
// after a while.
|
|
527
|
+
failures: (latestPrev?.failures ?? 0) + 1,
|
|
528
|
+
failingSince: latestPrev?.failingSince ?? input.date,
|
|
529
|
+
});
|
|
530
|
+
return { ran: true, reason: "failed", switch: sw, code: read.code };
|
|
531
|
+
}
|
|
532
|
+
const seen = latestPrev?.latest === read.latest && latestPrev?.latestSeen !== undefined ? latestPrev.latestSeen : input.date;
|
|
533
|
+
writeUpdateState(input.configPath, {
|
|
534
|
+
switch: "none",
|
|
535
|
+
at,
|
|
536
|
+
checkedDate: input.date,
|
|
537
|
+
okAt: at,
|
|
538
|
+
latest: read.latest,
|
|
539
|
+
latestSeen: seen,
|
|
540
|
+
flags: { tellBelow: read.tellBelow, urgentBelow: read.urgentBelow, tellBehind: read.tellBehind, plugin: read.plugin },
|
|
541
|
+
});
|
|
542
|
+
return { ran: true, reason: "ok", switch: sw, latest: read.latest };
|
|
543
|
+
} catch {
|
|
544
|
+
return { ran: false, reason: "failed", switch: sw, code: "state" };
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// ── the lines ─────────────────────────────────────────────────────────────
|
|
549
|
+
|
|
550
|
+
/** What the wake has told (`UPDATE_TOLD_KEY`). */
|
|
551
|
+
interface Told {
|
|
552
|
+
tell?: string;
|
|
553
|
+
urgent?: { floor: string; dates: string[] };
|
|
554
|
+
/** The `latest` an exhausted urgent floor was last told as an ordinary line for (design Q4: "then once per version"). */
|
|
555
|
+
urgentAfter?: string;
|
|
556
|
+
behind?: { latest: string; installed: string; gap: number; date: string };
|
|
557
|
+
offered?: string;
|
|
558
|
+
/** The release date the age line was said for: once per copy. */
|
|
559
|
+
age?: string;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function readTold(raw: string | undefined): Told {
|
|
563
|
+
if (raw === undefined) return {};
|
|
564
|
+
try {
|
|
565
|
+
const v: unknown = JSON.parse(raw);
|
|
566
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Told) : {};
|
|
567
|
+
} catch {
|
|
568
|
+
return {};
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function daysBetween(a: string, b: string): number {
|
|
573
|
+
return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86_400_000);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
export interface UpdateLineInput {
|
|
577
|
+
readonly store: Store;
|
|
578
|
+
readonly configPath: string | undefined;
|
|
579
|
+
readonly config: AdapterConfig;
|
|
580
|
+
readonly env: Record<string, string | undefined>;
|
|
581
|
+
readonly home: string;
|
|
582
|
+
/** How this copy came. */
|
|
583
|
+
readonly route: InstallRoute;
|
|
584
|
+
/** The version a person has installed: npm's running `package.json`; for the plugin, the highest Claude Code records (an updated, unreloaded window is not told to update). */
|
|
585
|
+
readonly installed: string | null;
|
|
586
|
+
/** This copy's release date, `YYYY-MM-DD` (`RELEASE_DATE` above). */
|
|
587
|
+
readonly released: string;
|
|
588
|
+
readonly today: string;
|
|
589
|
+
/** The directory flavor (`runtime.ts#TRANSPILED`): makes no check and reads nothing of Claude Code's. */
|
|
590
|
+
readonly transpiled: boolean;
|
|
591
|
+
/** The sidebar plugin is recorded (it and the stood-down core plugin need the plugin step too). */
|
|
592
|
+
readonly sidebar?: boolean;
|
|
593
|
+
readonly codeTab?: boolean;
|
|
594
|
+
readonly runtime?: RuntimeKind;
|
|
595
|
+
/** Today is the day the first meeting was (last) offered: that day belongs to the meeting. */
|
|
596
|
+
readonly meetingDay?: boolean;
|
|
597
|
+
/** This wake already carries the urgent line: no second update line beside it. */
|
|
598
|
+
readonly urgentSaid?: boolean;
|
|
599
|
+
/**
|
|
600
|
+
* Whether this line fits the envelope it would join. A line that does not
|
|
601
|
+
* fit is NOT claimed — nothing is marked told — so the next wake says it.
|
|
602
|
+
* Absent: it fits.
|
|
603
|
+
*/
|
|
604
|
+
readonly fits?: (line: string) => boolean;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
const PLUGIN_STEP_SHORT = "/plugin → Marketplaces → counterparts → Update marketplace";
|
|
608
|
+
|
|
609
|
+
/** Steps for this install's route, lower-case, no closing stop. Short: the wake is near its ceiling. */
|
|
610
|
+
export function updateSteps(input: Pick<UpdateLineInput, "route" | "sidebar" | "codeTab" | "runtime"> & { readonly market: PluginMarket }): string {
|
|
611
|
+
const npm = `run ${npmUpdateCommand(input.runtime)}, then restart Claude Code`;
|
|
612
|
+
const reload = input.codeTab === true ? "then start a new session" : "then /reload-plugins in each open window";
|
|
613
|
+
const plugin =
|
|
614
|
+
input.market === "synced"
|
|
615
|
+
? PLUGIN_UPDATE_SYNCED
|
|
616
|
+
: `${input.market === "claude-community" ? PLUGIN_UPDATE_COMMUNITY.replace(/^in Claude Code, /, "") : PLUGIN_STEP_SHORT}, ${reload}`;
|
|
617
|
+
if (input.route === "npm") return input.sidebar === true ? `${npm}; and ${PLUGIN_STEP_SHORT}` : npm;
|
|
618
|
+
if (input.route === "plugin") return plugin;
|
|
619
|
+
return `npm: ${npm} · plugin: ${plugin}`;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** The urgent line's step: shorter still. */
|
|
623
|
+
function shortStep(route: InstallRoute, market: PluginMarket, runtime: RuntimeKind | undefined): string {
|
|
624
|
+
const npm = npmUpdateCommand(runtime);
|
|
625
|
+
const plugin = market === "synced" ? "restart Claude Code" : `/plugin → Marketplaces → ${market === "claude-community" ? "claude-community" : "counterparts"} → Update marketplace`;
|
|
626
|
+
if (route === "npm") return npm;
|
|
627
|
+
if (route === "plugin") return plugin;
|
|
628
|
+
return `${npm}, or ${plugin}`;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
function marketOf(input: UpdateLineInput): PluginMarket {
|
|
632
|
+
return input.route === "npm" ? null : pluginMarket({ home: input.home, env: input.env });
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** The person's switch, as this process sees it (config, the store's `asked`, this environment). */
|
|
636
|
+
function switchHere(input: UpdateLineInput): UpdateSwitch {
|
|
637
|
+
return updateSwitch({ config: input.config, asked: askedOff(input.store), env: input.env });
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* WHAT THE WORKER'S RECORD LETS THIS ROUTE BE TOLD — the wake's rule, and
|
|
642
|
+
* doctor's (constitution 16: one vocabulary). A plugin install waits until the
|
|
643
|
+
* day after a version was first seen (npm goes live before the plugin tag),
|
|
644
|
+
* and is never told about a release whose plugin pin is held (`plugin: false`).
|
|
645
|
+
*/
|
|
646
|
+
export function knownLatestFor(route: InstallRoute, state: UpdateState | null, today: string): { latest: string; flags: ReleaseFlags } | null {
|
|
647
|
+
if (state === null || state.latest === undefined || state.latest === null || state.flags === undefined) return null;
|
|
648
|
+
if (route !== "npm") {
|
|
649
|
+
if (state.flags.plugin === false) return null;
|
|
650
|
+
if (state.latestSeen === undefined || state.latestSeen >= today) return null;
|
|
651
|
+
}
|
|
652
|
+
return { latest: state.latest, flags: state.flags };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
function quiet(input: UpdateLineInput): boolean {
|
|
656
|
+
return input.config.observer === true || input.meetingDay === true || input.installed === null;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
const fitsOf = (input: UpdateLineInput) => (line: string): boolean => input.fits === undefined || input.fits(line);
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* THE URGENT LINE, or null: installed below the release's `urgentBelow`.
|
|
663
|
+
* Once a day on at most `URGENT_DAYS` days per floor. Claimed here, and only
|
|
664
|
+
* when it fits. Never throws.
|
|
665
|
+
*/
|
|
666
|
+
export function urgentUpdateLine(input: UpdateLineInput): string | null {
|
|
667
|
+
try {
|
|
668
|
+
if (quiet(input) || switchHere(input) !== "none" || input.configPath === undefined) return null;
|
|
669
|
+
const known = knownLatestFor(input.route, readUpdateState(input.configPath), input.today);
|
|
670
|
+
const installed = input.installed as string;
|
|
671
|
+
const floor = known?.flags.urgentBelow ?? null;
|
|
672
|
+
if (known === null || floor === null || !versionBelow(installed, floor)) return null;
|
|
673
|
+
const line = `${UPDATE_URGENT_LEAD} "Please update Counterparts soon (${installed} → ${known.latest}, a fix): ${shortStep(input.route, marketOf(input), input.runtime)}."`;
|
|
674
|
+
if (!fitsOf(input)(line)) return null;
|
|
675
|
+
const claimed = input.store.updateMeta(UPDATE_TOLD_KEY, (current) => {
|
|
676
|
+
const told = readTold(current);
|
|
677
|
+
const dates = told.urgent?.floor === floor ? told.urgent.dates : [];
|
|
678
|
+
if (dates.length >= URGENT_DAYS || dates.includes(input.today)) return undefined;
|
|
679
|
+
return JSON.stringify({ ...told, urgent: { floor, dates: [...dates, input.today] } });
|
|
680
|
+
});
|
|
681
|
+
return typeof claimed === "string" ? line : null;
|
|
682
|
+
} catch {
|
|
683
|
+
return null;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* THE ONE OTHER UPDATE LINE, or null, in this order:
|
|
689
|
+
* 1. **tell** (installed below `tellBelow`, once per floor), **behind**
|
|
690
|
+
* (`tellBehind` or more releases behind; again only at N more, or after
|
|
691
|
+
* `RETELL_DAYS`), or an urgent floor whose `URGENT_DAYS` are spent (once
|
|
692
|
+
* per newest version) — carrying the auto-update offer when it is due;
|
|
693
|
+
* 2. **the auto-update offer**, once ever, for a plugin copy from our
|
|
694
|
+
* marketplace or the community one whose auto-update is not on and
|
|
695
|
+
* whose toggle is not hidden;
|
|
696
|
+
* 3. **the age line**, for a copy that makes no check (the directory
|
|
697
|
+
* flavor, Claude Code's no-traffic switch, a check failing for
|
|
698
|
+
* `FAILING_DAYS`): over `AGE_DAYS` old, once per copy.
|
|
699
|
+
* Nothing at all when the person said no (`personSaidNo`), under observer,
|
|
700
|
+
* on the meeting's day, or in a wake that already carries the urgent line.
|
|
701
|
+
* Claimed here, and only when it fits. Never throws.
|
|
702
|
+
*/
|
|
703
|
+
export function updateNoticeLine(input: UpdateLineInput): string | null {
|
|
704
|
+
try {
|
|
705
|
+
if (quiet(input) || input.urgentSaid === true) return null;
|
|
706
|
+
const sw = switchHere(input);
|
|
707
|
+
if (personSaidNo(sw)) return null;
|
|
708
|
+
const fits = fitsOf(input);
|
|
709
|
+
const installed = input.installed as string;
|
|
710
|
+
const market = marketOf(input);
|
|
711
|
+
const steps = updateSteps({ ...input, market });
|
|
712
|
+
const state = input.configPath === undefined || input.transpiled ? null : readUpdateState(input.configPath);
|
|
713
|
+
const autoOn = state?.autoUpdate === true || (!input.transpiled && market !== null && market !== "synced" && claudeAutoUpdate({ home: input.home, env: input.env, market }));
|
|
714
|
+
const offerable = input.route === "plugin" && market !== null && market !== "synced" && !autoOn && !autoUpdateHidden(input.env);
|
|
715
|
+
const offerStep = `/plugin → Marketplaces → ${String(market)} → Enable auto-update`;
|
|
716
|
+
const known = sw === "none" ? knownLatestFor(input.route, state, input.today) : null;
|
|
717
|
+
|
|
718
|
+
if (known !== null) {
|
|
719
|
+
const gap = releasesBehind(installed, known.latest);
|
|
720
|
+
let said: string | null = null;
|
|
721
|
+
const claimed = input.store.updateMeta(UPDATE_TOLD_KEY, (current) => {
|
|
722
|
+
const told = readTold(current);
|
|
723
|
+
const tellFloor = known.flags.tellBelow;
|
|
724
|
+
const urgentFloor = known.flags.urgentBelow;
|
|
725
|
+
const offering = offerable && told.offered === undefined;
|
|
726
|
+
const next: Told = { ...told, ...(offering ? { offered: input.today } : {}) };
|
|
727
|
+
// An urgent day already told (another window, earlier today): nothing
|
|
728
|
+
// ordinary beside it on the same day.
|
|
729
|
+
if (urgentFloor !== null && versionBelow(installed, urgentFloor) && told.urgent?.floor === urgentFloor && told.urgent.dates.includes(input.today)) {
|
|
730
|
+
return undefined;
|
|
731
|
+
}
|
|
732
|
+
const urgentSpent =
|
|
733
|
+
urgentFloor !== null &&
|
|
734
|
+
versionBelow(installed, urgentFloor) &&
|
|
735
|
+
told.urgent?.floor === urgentFloor &&
|
|
736
|
+
told.urgent.dates.length >= URGENT_DAYS &&
|
|
737
|
+
!told.urgent.dates.includes(input.today);
|
|
738
|
+
if (tellFloor !== null && versionBelow(installed, tellFloor) && told.tell !== tellFloor) {
|
|
739
|
+
next.tell = tellFloor;
|
|
740
|
+
} else if (urgentSpent && told.urgentAfter !== known.latest) {
|
|
741
|
+
next.urgentAfter = known.latest;
|
|
742
|
+
} else if (gap >= known.flags.tellBehind) {
|
|
743
|
+
const b = told.behind;
|
|
744
|
+
const fresh = b === undefined || b.installed !== installed;
|
|
745
|
+
const due = fresh || gap >= b.gap + known.flags.tellBehind || daysBetween(b.date, input.today) >= RETELL_DAYS;
|
|
746
|
+
if (!due) return undefined;
|
|
747
|
+
next.behind = { latest: known.latest, installed, gap, date: input.today };
|
|
748
|
+
} else {
|
|
749
|
+
return undefined;
|
|
750
|
+
}
|
|
751
|
+
const line = `${UPDATE_LEAD} "Counterparts ${known.latest} is out (I'm on ${installed}). To update: ${steps}.${offering ? ` Or turn on auto-update: ${offerStep}.` : ""}" ${STOP_HINT}`;
|
|
752
|
+
if (!fits(line)) return undefined;
|
|
753
|
+
said = line;
|
|
754
|
+
return JSON.stringify(next);
|
|
755
|
+
});
|
|
756
|
+
if (typeof claimed === "string" && said !== null) return said;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
if (offerable) {
|
|
760
|
+
const line = `${UPDATE_LEAD} "Claude Code can keep me current: ${offerStep}." ${STOP_HINT}`;
|
|
761
|
+
if (fits(line)) {
|
|
762
|
+
const claimed = input.store.updateMeta(UPDATE_TOLD_KEY, (current) => {
|
|
763
|
+
const told = readTold(current);
|
|
764
|
+
return told.offered === undefined ? JSON.stringify({ ...told, offered: input.today }) : undefined;
|
|
765
|
+
});
|
|
766
|
+
if (typeof claimed === "string") return line;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
const failing = state?.failingSince !== undefined && daysBetween(state.failingSince, input.today) >= FAILING_DAYS;
|
|
771
|
+
const noCheck = input.transpiled || sw === "nonessential" || failing;
|
|
772
|
+
if (noCheck && DATE.test(input.released) && daysBetween(input.released, input.today) > AGE_DAYS) {
|
|
773
|
+
// `Oct 28`, or the date as written in another year (`time.ts#shortDay`: dates are time.ts's to format).
|
|
774
|
+
const when = shortDay(input.released, yearOf(input.today));
|
|
775
|
+
const line = `${UPDATE_LEAD} "This Counterparts is from ${when}; a newer one may be out. If you'd like it: ${steps}." ${STOP_HINT}`;
|
|
776
|
+
if (fits(line)) {
|
|
777
|
+
const claimed = input.store.updateMeta(UPDATE_TOLD_KEY, (current) => {
|
|
778
|
+
const told = readTold(current);
|
|
779
|
+
return told.age === input.released ? undefined : JSON.stringify({ ...told, age: input.released });
|
|
780
|
+
});
|
|
781
|
+
if (typeof claimed === "string") return line;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return null;
|
|
785
|
+
} catch {
|
|
786
|
+
return null;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/** The installed version a plugin window is judged by: the highest of what it runs and what Claude Code records. */
|
|
791
|
+
export function installedForRoute(route: InstallRoute, running: string | null, recorded: () => string | null): string | null {
|
|
792
|
+
if (route !== "plugin") return running;
|
|
793
|
+
let rec: string | null = null;
|
|
794
|
+
try {
|
|
795
|
+
rec = recorded();
|
|
796
|
+
} catch {
|
|
797
|
+
rec = null;
|
|
798
|
+
}
|
|
799
|
+
if (rec === null) return running;
|
|
800
|
+
return running === null || versionBelow(running, rec) ? rec : running;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* THE MEETING'S DAY: the day the first meeting was last offered, or a wake
|
|
805
|
+
* that makes the offer now (re-check of #672: the offer is recorded only after
|
|
806
|
+
* the wake is built, so a fresh install's first wake read as "no offer yet"
|
|
807
|
+
* and carried "Enable auto-update" beside the meeting). Never throws: a store
|
|
808
|
+
* that will not say is not the meeting's day.
|
|
809
|
+
*/
|
|
810
|
+
function meetingDay(store: Store, today: string, session: string): boolean {
|
|
811
|
+
try {
|
|
812
|
+
if (lastOffer(store)?.on === today) return true;
|
|
813
|
+
return offerDue(store, { on: today, session }).due;
|
|
814
|
+
} catch {
|
|
815
|
+
return false;
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* THE LINES' INPUT FOR THIS PROCESS — what the session-start hook and
|
|
821
|
+
* Desktop's `wake` both pass: the version this person has installed (the
|
|
822
|
+
* plugin's highest record, so an updated window that has not reloaded is not
|
|
823
|
+
* told to update), this copy's release date and flavor, the sidebar (npm
|
|
824
|
+
* route only, full flavor only: the directory flavor reads nothing of Claude
|
|
825
|
+
* Code's), and whether today is the first meeting's day (the day it was last
|
|
826
|
+
* offered — not "still pending": a person who said "later" and never came back
|
|
827
|
+
* must still hear of an urgent fix).
|
|
828
|
+
*/
|
|
829
|
+
export function updateLineInputHere(input: {
|
|
830
|
+
readonly store: Store;
|
|
831
|
+
readonly configPath: string | undefined;
|
|
832
|
+
readonly config: AdapterConfig;
|
|
833
|
+
readonly route: InstallRoute;
|
|
834
|
+
readonly today: string;
|
|
835
|
+
readonly env?: Record<string, string | undefined>;
|
|
836
|
+
readonly home: string;
|
|
837
|
+
readonly cwd?: string | null;
|
|
838
|
+
readonly codeTab?: boolean;
|
|
839
|
+
/** This session's id, for whether this very wake makes the meeting offer; absent, any session. */
|
|
840
|
+
readonly session?: string;
|
|
841
|
+
}): UpdateLineInput {
|
|
842
|
+
const env = input.env ?? process.env;
|
|
843
|
+
const cwd = input.cwd ?? null;
|
|
844
|
+
const installed = installedForRoute(input.route, installedVersion(), () =>
|
|
845
|
+
TRANSPILED ? null : recordedForThisCopy({ home: input.home, env, cwd }),
|
|
846
|
+
);
|
|
847
|
+
let sidebar = false;
|
|
848
|
+
if (input.route === "npm" && !TRANSPILED) {
|
|
849
|
+
try {
|
|
850
|
+
sidebar = sidebarPluginRecorded({ home: input.home, env, cwd });
|
|
851
|
+
} catch {
|
|
852
|
+
sidebar = false;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
return {
|
|
856
|
+
store: input.store,
|
|
857
|
+
configPath: input.configPath,
|
|
858
|
+
config: input.config,
|
|
859
|
+
env,
|
|
860
|
+
home: input.home,
|
|
861
|
+
route: input.route,
|
|
862
|
+
installed,
|
|
863
|
+
released: RELEASE_DATE,
|
|
864
|
+
today: input.today,
|
|
865
|
+
transpiled: TRANSPILED,
|
|
866
|
+
sidebar,
|
|
867
|
+
codeTab: input.codeTab === true,
|
|
868
|
+
meetingDay: meetingDay(input.store, input.today, input.session ?? ""),
|
|
869
|
+
};
|
|
870
|
+
}
|