ccdeck 3.49.1 → 3.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +7 -3
  2. package/THIRD_PARTY_NOTICES.md +28 -0
  3. package/bin/cli/commands.js +34 -3
  4. package/bin/cli/second-start.js +6 -1
  5. package/dist/web/assets/BrowserWatchModal-CDpunrq9.js +1 -0
  6. package/dist/web/assets/IntegrationModal-BctMcNU8.js +7 -0
  7. package/dist/web/assets/{RadioPanel-gFYxdsBg.js → RadioPanel-DQNFtYOx.js} +1 -1
  8. package/dist/web/assets/{TrafficRadar-B9MfKca4.js → TrafficRadar-DRt3Al7E.js} +1 -1
  9. package/dist/web/assets/UsageHistoryModal-DlgPufgs.js +1 -0
  10. package/dist/web/assets/{app-D2NP6IPl.js → app-4x4wTE-L.js} +73 -73
  11. package/dist/web/assets/{app-DfGYllmZ.css → app-o4kL0FgZ.css} +1 -1
  12. package/dist/web/assets/{index-Be6Ox-74.js → index-CWUj8Kqh.js} +1 -1
  13. package/dist/web/index.html +3 -3
  14. package/node_modules/bare-addon-resolve/LICENSE +201 -0
  15. package/node_modules/bare-addon-resolve/README.md +226 -0
  16. package/node_modules/bare-addon-resolve/index.d.ts +100 -0
  17. package/node_modules/bare-addon-resolve/index.js +531 -0
  18. package/node_modules/bare-addon-resolve/lib/errors.d.ts +16 -0
  19. package/node_modules/bare-addon-resolve/lib/errors.js +21 -0
  20. package/node_modules/bare-addon-resolve/package.json +57 -0
  21. package/node_modules/bare-module-resolve/LICENSE +201 -0
  22. package/node_modules/bare-module-resolve/README.md +322 -0
  23. package/node_modules/bare-module-resolve/index.d.ts +171 -0
  24. package/node_modules/bare-module-resolve/index.js +899 -0
  25. package/node_modules/bare-module-resolve/lib/errors.d.ts +31 -0
  26. package/node_modules/bare-module-resolve/lib/errors.js +37 -0
  27. package/node_modules/bare-module-resolve/package.json +56 -0
  28. package/node_modules/bare-semver/LICENSE +201 -0
  29. package/node_modules/bare-semver/README.md +147 -0
  30. package/node_modules/bare-semver/index.d.ts +61 -0
  31. package/node_modules/bare-semver/index.js +13 -0
  32. package/node_modules/bare-semver/lib/comparator.js +37 -0
  33. package/node_modules/bare-semver/lib/constants.js +7 -0
  34. package/node_modules/bare-semver/lib/errors.js +22 -0
  35. package/node_modules/bare-semver/lib/range.js +256 -0
  36. package/node_modules/bare-semver/lib/version.js +240 -0
  37. package/node_modules/bare-semver/package.json +43 -0
  38. package/node_modules/fs-native-extensions/CMakeLists.txt +118 -0
  39. package/node_modules/fs-native-extensions/LICENSE +201 -0
  40. package/node_modules/fs-native-extensions/README.md +160 -0
  41. package/node_modules/fs-native-extensions/binding.c +1825 -0
  42. package/node_modules/fs-native-extensions/binding.js +3 -0
  43. package/node_modules/fs-native-extensions/include/fs-ext.h +193 -0
  44. package/node_modules/fs-native-extensions/index.js +356 -0
  45. package/node_modules/fs-native-extensions/package.json +72 -0
  46. package/node_modules/fs-native-extensions/prebuilds/android-arm/fs-native-extensions.bare +0 -0
  47. package/node_modules/fs-native-extensions/prebuilds/android-arm/fs-native-extensions.node +0 -0
  48. package/node_modules/fs-native-extensions/prebuilds/android-arm64/fs-native-extensions.bare +0 -0
  49. package/node_modules/fs-native-extensions/prebuilds/android-arm64/fs-native-extensions.node +0 -0
  50. package/node_modules/fs-native-extensions/prebuilds/android-ia32/fs-native-extensions.bare +0 -0
  51. package/node_modules/fs-native-extensions/prebuilds/android-ia32/fs-native-extensions.node +0 -0
  52. package/node_modules/fs-native-extensions/prebuilds/android-x64/fs-native-extensions.bare +0 -0
  53. package/node_modules/fs-native-extensions/prebuilds/android-x64/fs-native-extensions.node +0 -0
  54. package/node_modules/fs-native-extensions/prebuilds/darwin-arm64/fs-native-extensions.bare +0 -0
  55. package/node_modules/fs-native-extensions/prebuilds/darwin-arm64/fs-native-extensions.node +0 -0
  56. package/node_modules/fs-native-extensions/prebuilds/darwin-x64/fs-native-extensions.bare +0 -0
  57. package/node_modules/fs-native-extensions/prebuilds/darwin-x64/fs-native-extensions.node +0 -0
  58. package/node_modules/fs-native-extensions/prebuilds/ios-arm64/fs-native-extensions.bare +0 -0
  59. package/node_modules/fs-native-extensions/prebuilds/ios-arm64-simulator/fs-native-extensions.bare +0 -0
  60. package/node_modules/fs-native-extensions/prebuilds/ios-x64-simulator/fs-native-extensions.bare +0 -0
  61. package/node_modules/fs-native-extensions/prebuilds/linux-arm64/fs-native-extensions.bare +0 -0
  62. package/node_modules/fs-native-extensions/prebuilds/linux-arm64/fs-native-extensions.node +0 -0
  63. package/node_modules/fs-native-extensions/prebuilds/linux-x64/fs-native-extensions.bare +0 -0
  64. package/node_modules/fs-native-extensions/prebuilds/linux-x64/fs-native-extensions.node +0 -0
  65. package/node_modules/fs-native-extensions/prebuilds/win32-arm64/fs-native-extensions.bare +0 -0
  66. package/node_modules/fs-native-extensions/prebuilds/win32-arm64/fs-native-extensions.node +0 -0
  67. package/node_modules/fs-native-extensions/prebuilds/win32-x64/fs-native-extensions.bare +0 -0
  68. package/node_modules/fs-native-extensions/prebuilds/win32-x64/fs-native-extensions.node +0 -0
  69. package/node_modules/fs-native-extensions/src/apple.c +197 -0
  70. package/node_modules/fs-native-extensions/src/linux.c +146 -0
  71. package/node_modules/fs-native-extensions/src/platform.h +51 -0
  72. package/node_modules/fs-native-extensions/src/posix.c +33 -0
  73. package/node_modules/fs-native-extensions/src/shared.c +397 -0
  74. package/node_modules/fs-native-extensions/src/win32/nt.h +226 -0
  75. package/node_modules/fs-native-extensions/src/win32.c +531 -0
  76. package/node_modules/require-addon/LICENSE +201 -0
  77. package/node_modules/require-addon/README.md +19 -0
  78. package/node_modules/require-addon/lib/bare.js +1 -0
  79. package/node_modules/require-addon/lib/default.js +7 -0
  80. package/node_modules/require-addon/lib/node.js +79 -0
  81. package/node_modules/require-addon/package.json +64 -0
  82. package/node_modules/which-runtime/LICENSE +201 -0
  83. package/node_modules/which-runtime/README.md +29 -0
  84. package/node_modules/which-runtime/index.js +36 -0
  85. package/node_modules/which-runtime/package.json +32 -0
  86. package/package.json +12 -2
  87. package/release-notes.json +25 -0
  88. package/src/server/claude-accounts.mjs +19 -3
  89. package/src/server/claude-collector.mjs +18 -2
  90. package/src/server/cswap-install.mjs +60 -18
  91. package/src/server/integrations/jira-comment.mjs +37 -0
  92. package/src/server/integrations/jira-move.mjs +37 -11
  93. package/src/server/integrations/jira-transition.mjs +43 -0
  94. package/src/server/integrations/jira-write-guard.mjs +218 -0
  95. package/src/server/integrations/jira.mjs +16 -0
  96. package/src/server/integrations/routes.mjs +70 -7
  97. package/src/server/lan-deck.mjs +9 -0
  98. package/src/server/lan-engine.mjs +17 -2
  99. package/src/server/lan-manifest.mjs +10 -3
  100. package/src/server/lifecycle.mjs +27 -2
  101. package/src/server/login-guard.mjs +4 -0
  102. package/src/server/npm-upgrade.mjs +46 -18
  103. package/src/server/pinned-build.mjs +5 -0
  104. package/src/server/quota-store-resets.mjs +13 -6
  105. package/src/server/quota.mjs +8 -1
  106. package/src/server/running-deck.mjs +14 -0
  107. package/src/server/static-cache.mjs +34 -16
  108. package/src/server/terminal-cli-update.mjs +189 -0
  109. package/src/server/terminal-cli.mjs +93 -0
  110. package/src/server/traffic-radar-wire.mjs +6 -0
  111. package/src/server/usage-share.mjs +444 -0
  112. package/dist/web/assets/BrowserWatchModal-CCARqAMn.js +0 -1
  113. package/dist/web/assets/IntegrationModal-B8t53aE5.js +0 -7
  114. package/dist/web/assets/UsageHistoryModal-DvYWhsYv.js +0 -1
@@ -0,0 +1,218 @@
1
+ // Durable per-scope reservations. Only the small allowlisted record is stored.
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { chmod, link, mkdir, open, readFile, readdir, unlink } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { createConnection, createServer } from 'node:net';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { createRequire } from 'node:module';
8
+ import { dirname } from 'node:path';
9
+ import { integrationError } from './errors.mjs';
10
+ import { deckDataDir } from '../deck-home.mjs';
11
+ import { createTemp, renameWithRetry } from '../atomic-write.mjs';
12
+ import { STORE_DIR } from './store.mjs';
13
+
14
+ const require = createRequire(import.meta.url);
15
+ let binding;
16
+ function nativeLock() {
17
+ if (!binding) {
18
+ // The exact dependency version pins this N-API layout and ABI. Loading the
19
+ // shipped binding directly avoids its resolver's Node 20-only Array.with.
20
+ // Keep this lazy so unsupported targets can still run the read-only deck.
21
+ const root = dirname(require.resolve('fs-native-extensions/package.json'));
22
+ binding = require(join(root, 'prebuilds', `${process.platform}-${process.arch}`, 'fs-native-extensions.node'));
23
+ }
24
+ return binding;
25
+ }
26
+ const nativeLocks = {
27
+ tryLock(fd) {
28
+ try { nativeLock().tryLock(fd, 0, 0, true); return true; }
29
+ catch (err) { if (err.code === 'EAGAIN') return false; throw err; }
30
+ },
31
+ unlock(fd) { nativeLock().unlock(fd, 0, 0); },
32
+ };
33
+ const active = new Set();
34
+ const listeners = new Map();
35
+ const keyPattern = /^[A-Z][A-Z0-9_]{0,40}-[1-9]\d{0,11}$/;
36
+ const uuidPattern = /^[0-9a-f-]{36}$/;
37
+ const scope = record => createHash('sha256').update(JSON.stringify([record.connectionId, record.kind, record.kind === 'move' ? '' : record.issueKey])).digest('hex');
38
+ const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code !== 'ESRCH'; } };
39
+
40
+ // Ephemeral sockets identify live writers without trusting reusable PIDs.
41
+ // Scope synchronization uses OS file locks below, never a fixed TCP port.
42
+ function listen(port, handler = socket => socket.destroy()) {
43
+ return new Promise((resolve, reject) => {
44
+ const server = createServer(handler);
45
+ server.once('error', reject);
46
+ server.listen({ port, host: '127.0.0.1', exclusive: true }, () => {
47
+ server.removeListener('error', reject);
48
+ resolve(server);
49
+ });
50
+ });
51
+ }
52
+ const close = server => new Promise((resolve, reject) => server.close(err => err ? reject(err) : resolve()));
53
+ async function startMarker(op) {
54
+ const token = randomUUID();
55
+ let server;
56
+ do {
57
+ server = await listen(0, socket => {
58
+ socket.setTimeout(1000, () => socket.destroy());
59
+ socket.end(token);
60
+ });
61
+ } while (!server);
62
+ server.unref();
63
+ listeners.set(op.operationId, server);
64
+ return { port: server.address().port, token };
65
+ }
66
+ async function stopMarker(op) {
67
+ const server = listeners.get(op.operationId);
68
+ if (server) { listeners.delete(op.operationId); await close(server); }
69
+ }
70
+ function markerAlive(marker) {
71
+ return new Promise(resolve => {
72
+ let data = '';
73
+ let settled = false;
74
+ const socket = createConnection({ host: '127.0.0.1', port: marker.port });
75
+ const done = value => { if (!settled) { settled = true; socket.destroy(); resolve(value); } };
76
+ // Ambiguous failures are treated as live; never acknowledge on a timeout.
77
+ socket.setTimeout(1000, () => done(true));
78
+ socket.on('data', chunk => { data += chunk.toString(); if (data.length >= marker.token.length) done(data === marker.token); });
79
+ socket.on('end', () => done(data === marker.token));
80
+ socket.on('error', err => done(err.code !== 'ECONNREFUSED'));
81
+ });
82
+ }
83
+
84
+ export function createJiraWriteGuard({ dir = () => join(deckDataDir(), STORE_DIR, 'jira-write-guard'), locks = nativeLocks } = {}) {
85
+ async function prepare() {
86
+ const root = dir();
87
+ await mkdir(root, { recursive: true, mode: 0o700 });
88
+ if (process.platform !== 'win32') await chmod(root, 0o700);
89
+ return root;
90
+ }
91
+ async function syncDir(root) {
92
+ // Windows does not support opening directories for fsync.
93
+ if (process.platform === 'win32') return;
94
+ const h = await open(root, 'r'); try { await h.sync(); } finally { await h.close(); }
95
+ }
96
+ async function read(path) {
97
+ try { return JSON.parse(await readFile(path, 'utf8')); }
98
+ catch (e) { if (e.code === 'ENOENT') return null; throw e; }
99
+ }
100
+ async function running(root, op) {
101
+ if (active.has(op.operationId)) return true;
102
+ const names = await readdir(root);
103
+ const prefix = `running-${op.operationId}-`;
104
+ for (const name of names.filter(name => name.startsWith(prefix))) {
105
+ const marker = await read(join(root, name)).catch(err => {
106
+ // Older releases used empty PID-only marker files. Preserve their
107
+ // conservative behaviour while those processes may still be running.
108
+ if (err instanceof SyntaxError) return null;
109
+ throw err;
110
+ });
111
+ if (marker && Number.isInteger(marker.port) && marker.port > 0 && marker.port <= 65535 && typeof marker.token === 'string' && uuidPattern.test(marker.token)) {
112
+ if (await markerAlive(marker)) return true;
113
+ } else if (alive(Number(name.slice(prefix.length)))) return true;
114
+ }
115
+ return false;
116
+ }
117
+ async function state(root, op) { return { ...op, state: await running(root, op) ? 'pending' : op.state === 'confirmed' ? 'confirmed' : 'uncertain' }; }
118
+ async function lock(root, op, fn) {
119
+ // Keep the inode forever: unlinking/replacing a locked file would allow
120
+ // two processes to lock different inodes for the same scope. The kernel
121
+ // releases ownership on descriptor close or process death, not file age.
122
+ const handle = await open(join(root, `lock-${scope(op)}`), 'a+', 0o600);
123
+ let acquired = false;
124
+ try {
125
+ while (!(acquired = locks.tryLock(handle.fd))) await delay(10);
126
+ return await fn();
127
+ } finally {
128
+ try { if (acquired) locks.unlock(handle.fd); }
129
+ finally { await handle.close(); }
130
+ }
131
+ }
132
+ return {
133
+ async begin(input) {
134
+ const { connectionId, kind } = input;
135
+ if (typeof connectionId !== 'string' || !connectionId || connectionId.length > 64 || !['comment', 'status', 'move'].includes(kind)) throw new Error('Invalid guard scope');
136
+ const op = { connectionId, kind, ...(kind === 'move' ? { boardId: input.boardId, issueKeys: input.issueKeys } : { issueKey: input.issueKey }), operationId: randomUUID(), state: 'pending' };
137
+ if (kind === 'move' ? typeof op.boardId !== 'string' || !/^[1-9]\d{0,11}$/.test(op.boardId) || !Array.isArray(op.issueKeys) || op.issueKeys.length < 1 || op.issueKeys.length > 50 || op.issueKeys.some(k => !keyPattern.test(k)) : !keyPattern.test(op.issueKey)) throw new Error('Invalid guard issue keys');
138
+ const root = await prepare();
139
+ // Check the actual filesystem and native support before any Jira write.
140
+ try { await lock(root, op, async () => {}); }
141
+ catch { throw integrationError('unavailable', 'Jira writes are unavailable because this system cannot safely coordinate them.'); }
142
+ const path = join(root, `${scope(op)}.json`);
143
+ const marker = join(root, `running-${op.operationId}-${process.pid}`);
144
+ const temp = join(root, `tmp-${op.operationId}`);
145
+ let returned = false;
146
+ active.add(op.operationId);
147
+ try {
148
+ const identity = await startMarker(op);
149
+ const markerHandle = await open(marker, 'wx', 0o600);
150
+ try { await markerHandle.writeFile(JSON.stringify(identity)); } finally { await markerHandle.close(); }
151
+ const h = await open(temp, 'wx', 0o600);
152
+ try { await h.writeFile(JSON.stringify(op)); await h.sync(); } finally { await h.close(); }
153
+ try { await link(temp, path); }
154
+ catch (e) {
155
+ if (e.code !== 'EEXIST') throw e;
156
+ const existing = await read(path);
157
+ if (!existing) return await this.begin(input);
158
+ return { conflict: await state(root, existing) };
159
+ }
160
+ await syncDir(root);
161
+ returned = true;
162
+ return { operation: { ...op, state: 'pending' } };
163
+ } finally {
164
+ await unlink(temp).catch(() => {});
165
+ if (!returned) { active.delete(op.operationId); await stopMarker(op); await unlink(marker).catch(() => {}); }
166
+ }
167
+ },
168
+ async finish(op, outcome) {
169
+ const root = await prepare();
170
+ try {
171
+ if (outcome === true || outcome === 'confirmed') {
172
+ const result = await lock(root, op, async () => {
173
+ const path = join(root, `${scope(op)}.json`);
174
+ const current = await read(path);
175
+ if (current?.operationId !== op.operationId) return { ok: false };
176
+ if (outcome === true) await unlink(path);
177
+ else {
178
+ const { tmp, handle } = await createTemp(path, { mode: 0o600 });
179
+ try {
180
+ try { await handle.writeFile(JSON.stringify({ ...current, state: 'confirmed' })); await handle.sync(); }
181
+ finally { await handle.close(); }
182
+ await renameWithRetry(tmp, path);
183
+ } finally { await unlink(tmp).catch(() => {}); }
184
+ }
185
+ await syncDir(root);
186
+ return { ok: true };
187
+ });
188
+ if (!result.ok) throw new Error('Jira write guard could not finalize the operation');
189
+ }
190
+ } finally {
191
+ active.delete(op.operationId);
192
+ await stopMarker(op);
193
+ await unlink(join(root, `running-${op.operationId}-${process.pid}`)).catch(() => {});
194
+ }
195
+ },
196
+ async list(connectionId) {
197
+ const root = await prepare();
198
+ const names = (await readdir(root)).filter(n => /^[a-f0-9]{64}\.json$/.test(n));
199
+ const records = await Promise.all(names.map(n => read(join(root, n))));
200
+ return Promise.all(records.filter(x => x?.connectionId === connectionId).map(x => state(root, x)));
201
+ },
202
+ async acknowledge(connectionId, operationId) {
203
+ if (typeof operationId !== 'string' || !uuidPattern.test(operationId)) return { ok: false };
204
+ const root = await prepare();
205
+ const op = (await this.list(connectionId)).find(x => x.operationId === operationId);
206
+ if (!op) return { ok: false };
207
+ return lock(root, op, async () => {
208
+ const path = join(root, `${scope(op)}.json`);
209
+ const current = await read(path);
210
+ if (!current || current.operationId !== operationId) return { ok: false };
211
+ if (await running(root, current)) return { conflict: await state(root, current) };
212
+ await unlink(path); await syncDir(root);
213
+ return { ok: true };
214
+ });
215
+ },
216
+ };
217
+ }
218
+ export const jiraWriteGuard = createJiraWriteGuard();
@@ -29,6 +29,8 @@ import { errorResponse, integrationError, IntegrationError } from "./errors.mjs"
29
29
  import { createProxy, fetchImage, isLocalHost, isSafeTarget, normaliseBaseUrl, originOf } from "./proxy.mjs";
30
30
  import { createRouter } from "./registry.mjs";
31
31
  import { createJiraMover, readJiraMoveCapability } from "./jira-move.mjs";
32
+ import { createJiraTransition, jiraTransitions } from "./jira-transition.mjs";
33
+ import { createJiraComment } from "./jira-comment.mjs";
32
34
 
33
35
  export const MIN_SERVER_VERSION = [8, 14, 0];
34
36
  const ATLASSIAN_API = "https://api.atlassian.com";
@@ -875,6 +877,8 @@ export function registerJiraRoutes(router) {
875
877
  };
876
878
  });
877
879
 
880
+ router.get("issue/:key/transitions", async ctx => ({ transitions: await jiraTransitions(ctx.client, restBase(ctx.conn), issueKey(ctx.params)) }));
881
+
878
882
  /** Every subtask of one issue, whoever has it. */
879
883
  router.get("issue/:key/subtasks", async ctx => {
880
884
  const key = issueKey(ctx.params);
@@ -982,6 +986,8 @@ export function createJiraClient(conn, secret, { fetchImpl, apiOrigin } = {}) {
982
986
  conn,
983
987
  get cache() { return cache; },
984
988
  moveIssue,
989
+ addComment: createJiraComment({ secret, origins: () => origins.slice(), sign: signJira, authCheck: jiraAuthCheck, fetchImpl, rest: restBase(conn), cloud: isCloud(conn), invalidate: () => { cache = createCache(); } }),
990
+ transitionIssue: createJiraTransition({ secret, origins: () => origins.slice(), sign: signJira, authCheck: jiraAuthCheck, fetchImpl, reader: signal => ({ json: (url, opts = {}) => reader().json(url, { ...opts, signal }) }), rest: restBase(conn), invalidate: () => { cache = createCache(); } }),
985
991
  get allowedOrigins() { return origins.slice(); },
986
992
  async validate({ phase = "validate", signal } = {}) {
987
993
  const result = await validateJira(conn, secret, { phase, signal, client: list => proxy(list, phase, signal) }, { apiOrigin });
@@ -1018,6 +1024,16 @@ export async function jiraRoutes(client, method, subpath, searchParams, _req, {
1018
1024
  try { return await client.moveIssue(move[1], moveBody, signal); }
1019
1025
  catch (err) { return errorResponse(err); }
1020
1026
  }
1027
+ const transition = /^issue\/([A-Z][A-Z0-9_]{0,40}-[1-9]\d{0,11})\/transitions$/.exec(subpath);
1028
+ if (method === "POST" && transition) {
1029
+ if ([...searchParams].length) return errorResponse(integrationError("invalid", "Transition parameters belong in the JSON body."));
1030
+ try { return await client.transitionIssue(transition[1], moveBody, signal); } catch (err) { return errorResponse(err); }
1031
+ }
1032
+ const comment = /^issue\/([A-Z][A-Z0-9_]{0,40}-[1-9]\d{0,11})\/comment$/.exec(subpath);
1033
+ if (method === "POST" && comment) {
1034
+ if ([...searchParams].length) return errorResponse(integrationError("invalid", "Comment parameters belong in the JSON body."));
1035
+ try { return await client.addComment(comment[1], moveBody, signal); } catch (err) { return errorResponse(err); }
1036
+ }
1021
1037
  if (method !== "GET" && method !== "HEAD") return errorResponse(integrationError("invalid", "That Jira operation is not supported."));
1022
1038
  const route = jiraRouter.find(subpath);
1023
1039
  if (!route) return errorResponse(integrationError("not-found", "No such Jira read."));
@@ -38,6 +38,8 @@ import { errorBody, errorResponse, integrationError, isTypedError } from "./erro
38
38
  import { fetchImage, IMAGE_MAX_BYTES, isSafeTarget, normaliseBaseUrl, originOf, RASTER_TYPES, rasterTypeOf } from "./proxy.mjs";
39
39
  import { getProvider, isAvailable, providerList } from "./registry.mjs";
40
40
  import { integrationsStore } from "./store.mjs";
41
+ import { jiraWriteGuard } from "./jira-write-guard.mjs";
42
+ import { parseJiraMove } from "./jira-move.mjs";
41
43
  import "./providers.mjs";
42
44
 
43
45
  // ── one client per connection ───────────────────────────────────────────────
@@ -457,13 +459,19 @@ export async function handleIntegrations(req, res, url, deps = {}) {
457
459
  // The server's normal mutation authentication and CSRF gates still apply.
458
460
  const jiraMove = kind === "jira" && method === "POST" && rest.length === 3
459
461
  && rest[0] === "board" && /^[1-9]\d{0,11}$/.test(rest[1]) && rest[2] === "move";
460
- if (method !== "GET" && method !== "HEAD" && !jiraMove) return notAllowed(res);
462
+ const jiraTransition = kind === "jira" && method === "POST" && rest.length === 3 && rest[0] === "issue"
463
+ && /^[A-Z][A-Z0-9_]{0,40}-[1-9]\d{0,11}$/.test(rest[1]) && rest[2] === "transitions";
464
+ const jiraComment = kind === "jira" && method === "POST" && rest.length === 3 && rest[0] === "issue"
465
+ && /^[A-Z][A-Z0-9_]{0,40}-[1-9]\d{0,11}$/.test(rest[1]) && rest[2] === "comment";
466
+ const guardRead = kind === "jira" && rest.length === 1 && rest[0] === "write-guard" && (method === "GET" || method === "HEAD");
467
+ const guardAck = kind === "jira" && rest.length === 2 && rest[0] === "write-guard" && rest[1] === "acknowledge" && method === "POST";
468
+ if (method !== "GET" && method !== "HEAD" && !jiraMove && !jiraTransition && !jiraComment && !guardAck) return notAllowed(res);
461
469
  let moveBody;
462
- if (jiraMove) {
470
+ if (jiraMove || jiraTransition || jiraComment) {
463
471
  if (!/^application\/json(?:\s*;|$)/i.test(String(req.headers["content-type"] ?? ""))) {
464
472
  throw integrationError("invalid", "Send the move as application/json.");
465
473
  }
466
- const bytes = await readBytes(req, res, 4096).catch(err => { if (!res.headersSent) throw err; return null; });
474
+ const bytes = await readBytes(req, res, jiraComment ? 65536 : 4096).catch(err => { if (!res.headersSent) throw err; return null; });
467
475
  if (bytes === null) return;
468
476
  try { moveBody = JSON.parse(bytes.toString("utf8")); }
469
477
  catch { throw integrationError("invalid", "The move body is not valid JSON."); }
@@ -495,15 +503,70 @@ export async function handleIntegrations(req, res, url, deps = {}) {
495
503
  return notFound(res);
496
504
  }
497
505
  if (!conn || conn.kind !== kind) throw integrationError("not-found", "That connection is not there any more.");
506
+ const guard = deps.jiraWriteGuard ?? jiraWriteGuard;
507
+ if (guardRead) return answer(200, { ok: true, operations: await guard.list(id) });
508
+ if (guardAck) {
509
+ const body = await readJsonBody(req, res);
510
+ if (body == null) return;
511
+ const result = await guard.acknowledge(id, body.operationId);
512
+ if (!result.ok) return answer(409, { ok: false, code: "jira_write_guard_conflict", ...(result.conflict ? { operation: result.conflict } : {}) });
513
+ return answer(200, { ok: true });
514
+ }
498
515
  if (!isAvailable(provider)) throw unavailable(provider.label);
499
516
  const secret = hold(await store.secret(id));
500
517
  if (secret == null) throw integrationError("expired", "No token is saved for this connection. Reconnect it in Settings.");
501
- const client = clientFor(provider, conn, secret, { fetchImpl });
502
-
503
- const read = await provider.routes(client, method, rest.join("/"), url.searchParams, req, { signal, ...(jiraMove ? { moveBody } : {}) });
518
+ const mutation = jiraMove || jiraTransition || jiraComment;
519
+ let operation, attempted = false, possibleWrite = false;
520
+ let client;
521
+ if (mutation) {
522
+ const scope = jiraMove ? { kind: "move", boardId: rest[1], issueKeys: parseJiraMove(moveBody).issueKeys }
523
+ : { kind: jiraComment ? "comment" : "status", issueKey: rest[1] };
524
+ const reservation = await guard.begin({ connectionId: id, ...scope });
525
+ if (reservation.conflict) return answer(409, { ok: false, code: "jira_write_guard_conflict", operation: reservation.conflict });
526
+ operation = reservation.operation;
527
+ // A private client associates each upstream write with this request; reads
528
+ // and the existing cached client remain untouched.
529
+ const transport = fetchImpl ?? globalThis.fetch;
530
+ const trackedFetch = async (url, opts = {}) => {
531
+ const write = opts.method && !["GET", "HEAD"].includes(String(opts.method).toUpperCase());
532
+ if (!write) return transport(url, opts);
533
+ attempted = true;
534
+ try {
535
+ const response = await transport(url, opts);
536
+ // A response can come from an intermediary after the write reached
537
+ // Jira. No HTTP status alone proves the request had no effect.
538
+ possibleWrite = true;
539
+ return response;
540
+ } catch (err) { possibleWrite = true; throw err; }
541
+ };
542
+ try { client = provider.createClient(conn, secret, { fetchImpl: trackedFetch }); }
543
+ catch (err) { await guard.finish(operation, true); throw err; }
544
+ } else client = clientFor(provider, conn, secret, { fetchImpl });
545
+
546
+ let read;
547
+ try {
548
+ read = await provider.routes(client, method, rest.join("/"), url.searchParams, req, { signal, ...(mutation ? { moveBody } : {}) });
549
+ } catch (err) {
550
+ if (!operation || !possibleWrite) throw err;
551
+ // Preserve typed provider errors; an unexpected failure after a write
552
+ // must still give the caller the durable operation to reconcile.
553
+ read = errorResponse(err);
554
+ } finally {
555
+ if (mutation && attempted) forgetConnection(id);
556
+ if (operation) {
557
+ const confirmed = read?.status >= 200 && read.status < 300 && read?.body?.ok === true;
558
+ await guard.finish(operation, confirmed ? 'confirmed' : !attempted || !possibleWrite);
559
+ }
560
+ }
504
561
  if (res.writableEnded || signal.aborted) return;
505
562
  const status = Number.isInteger(read?.status) ? read.status : 500;
506
- return answer(status, read?.body ?? errorBody(null));
563
+ const body = read?.body ?? errorBody(null);
564
+ if (operation && status >= 200 && status < 300 && body.ok === true) return answer(status, { ...body, operationId: operation.operationId });
565
+ if (operation && possibleWrite) {
566
+ const current = (await guard.list(id)).find(entry => entry.operationId === operation.operationId);
567
+ if (current) return answer(status, { ...body, operation: current });
568
+ }
569
+ return answer(status, body);
507
570
  } catch (err) {
508
571
  if (isTypedError(err)) {
509
572
  const { status, body } = errorResponse(err);
@@ -26,6 +26,7 @@ import { portHolder } from "./port-holder.mjs";
26
26
  import { createRouteCheck } from "./route-via.mjs";
27
27
  import { DISCOVERY_PORT } from "./lan-beacon.mjs";
28
28
  import { aboutThisDeck } from "./lan-about.mjs";
29
+ import { createUsageShare } from "./usage-share.mjs";
29
30
  import { MAC_FW, PROBE_PS, UFW_CONF, UFW_DEFAULTS, isActive, localAliases, reachability, readMacProbe, readProbe, readUfw, silentInbound } from "./lan-reach.mjs";
30
31
  import { run } from "./exec.mjs";
31
32
  // A LAN round checks the imports it lands the way the paste box does.
@@ -73,6 +74,14 @@ export const lanEngine = createEngine({
73
74
  // nobody else. RUNNING_VERSION rather than a fresh read, for the reason it
74
75
  // is read at import: it is what this process actually runs.
75
76
  about: aboutThisDeck({ version: RUNNING_VERSION }),
77
+ // One paired deck polls each account they share and the others take its
78
+ // reading, so the same account is not polled once per machine (#930).
79
+ usage: deps => createUsageShare({
80
+ ...deps,
81
+ register: true,
82
+ canImport: async () => (await import("./cswap-install.mjs")).cswapImportsUsage(),
83
+ readStore: async () => (await import("./claude-accounts.mjs")).storedUsageReadings(),
84
+ }),
76
85
  readAccounts: async () => {
77
86
  const { fetchClaudeAccounts } = await import("./claude-accounts.mjs");
78
87
  const got = await fetchClaudeAccounts();
@@ -299,6 +299,12 @@ export function createEngine({
299
299
  /** Where the machine would send each broadcast, so none leaves through a
300
300
  * tunnel — see route-via.mjs. Absent, every broadcast goes. */
301
301
  routes = null,
302
+ /** The usage readings this deck shares with paired decks so one of them
303
+ * polls each account (usage-share.mjs), or nothing for a deck that shares
304
+ * none — which is what the suite's engines are unless a test says. A
305
+ * function is called with what only the engine knows: `{ now, myFp,
306
+ * peerName }`. */
307
+ usage: usageOption = null,
302
308
  } = {}) {
303
309
  let cfg = {
304
310
  // `onward`: which of `shared` an arrival ticked rather than a person — see
@@ -424,14 +430,23 @@ export function createEngine({
424
430
  /** This deck's accounts in the shape the rules want — see lan-accounts.mjs.
425
431
  * Read through the same function the panel uses, so a row can never be alive
426
432
  * here and dead there. */
427
- const localAccounts = async () => syncAccounts(await readAccounts());
433
+ const usage = typeof usageOption === "function"
434
+ ? usageOption({ now, myFp: () => identity?.fp ?? null, peerName: fp => trustedPeer(cfg.trusted, fp)?.name ?? null })
435
+ : usageOption;
436
+ const localAccounts = async () => {
437
+ const accounts = syncAccounts(await readAccounts());
438
+ // Every manifest is built from this read, so the readings it carries and
439
+ // the accounts it names come from one moment.
440
+ await usage?.refresh(accounts);
441
+ return accounts;
442
+ };
428
443
 
429
444
  /** This deck's side of the manifest exchange: the frame it sends, what it
430
445
  * keeps of the one it hears — a paired deck's card and the logins it offers,
431
446
  * kept apart from lastRound — and what a row reads of that — see
432
447
  * lan-manifest.mjs. */
433
448
  const { manifestFrame, keepManifest, heardOf } = createManifests({
434
- about, now, myFp: () => identity.fp, settings: () => cfg,
449
+ about, now, myFp: () => identity.fp, settings: () => cfg, usage,
435
450
  });
436
451
 
437
452
  /**
@@ -12,9 +12,10 @@ import { openAbout, sealAbout } from "./lan-about.mjs";
12
12
  * is the engine's clock. `myFp` answers this deck's fingerprint as it is at
13
13
  * the moment of asking — a restart for a new key changes it — and `settings`
14
14
  * the settings in force, of which a manifest reads `shared`, `onward`,
15
- * `trusted`, `shareActive` and `sendInUse`.
15
+ * `trusted`, `shareActive` and `sendInUse`. `usage` is the deck's side of the
16
+ * usage readings paired decks share (usage-share.mjs), or null for none.
16
17
  */
17
- export function createManifests({ about, now, myFp, settings }) {
18
+ export function createManifests({ about, now, myFp, settings, usage = null }) {
18
19
  /** What each paired deck said about itself — version, operating system,
19
20
  * architecture — keyed by fingerprint, most recent only. Filled from both
20
21
  * directions: the manifest a deck answers with, and the question a deck that
@@ -42,10 +43,14 @@ export function createManifests({ about, now, myFp, settings }) {
42
43
  const manifestFrame = (accounts, key, toFp) => {
43
44
  const cfg = settings();
44
45
  const shared = sharedWith(cfg, toFp);
46
+ const list = manifestFor(accounts, shared, { sendInUse: cfg.sendInUse === true, shareActive: cfg.shareActive });
45
47
  return {
46
- t: "manifest", accounts: manifestFor(accounts, shared, { sendInUse: cfg.sendInUse === true, shareActive: cfg.shareActive }),
48
+ t: "manifest", accounts: list,
47
49
  ...currentFor(accounts, shared, cfg.shareActive),
48
50
  ...cardFor(key, toFp),
51
+ // The readings this deck owns for accounts in `list`, sealed like the
52
+ // card. An older deck ignores the key, as it ignores the card.
53
+ ...(usage ? usage.fieldFor(key, toFp, list) : {}),
49
54
  };
50
55
  };
51
56
 
@@ -63,6 +68,8 @@ export function createManifests({ about, now, myFp, settings }) {
63
68
  if (!Array.isArray(frame.accounts)) return null;
64
69
  const list = offered(frame.accounts);
65
70
  offersBy.set(fromFp, { at: now(), accounts: list, current: heardCurrent(frame.current, list) });
71
+ // Never awaited: handing a reading to claude-swap runs behind the round.
72
+ usage?.heard(key, frame, fromFp, list);
66
73
  return list;
67
74
  };
68
75
 
@@ -29,6 +29,7 @@ import { presentsDeckToken } from "./request-gates.mjs";
29
29
  // The version this process runs, read at boot by a leaf so that the LAN
30
30
  // engine's card and /api/version give one answer — see running-version.mjs.
31
31
  import { RUNNING_VERSION } from "./running-version.mjs";
32
+ import { terminalCliState, updateTerminalCli } from "./terminal-cli-update.mjs";
32
33
 
33
34
  // Resolved the way pinned-build.mjs resolves it, from a file in the same
34
35
  // directory, so every lazy import below is the URL the pin has already evaluated.
@@ -142,8 +143,13 @@ async function handleVersion(req, res) {
142
143
  // `dash` argument on purpose: the glyph tier is a terminal concern, and the
143
144
  // default em dash is what a browser should get.
144
145
  const rename = renameNotice({ invoked, pkgRoot: PKG_ROOT });
146
+ // The ccdeck a terminal here starts, when it is older than this deck: its
147
+ // commands are the old one's, and only the deck can say so (terminal-cli.mjs)
148
+ // — or replace it, which it says too (terminal-cli-update.mjs). A fact about
149
+ // this process's PATH, like the two above, so attached here too.
145
150
  send(res, 200, {
146
151
  ...report, canRestart: canRestartNow(), invokedAs: invoked, renameFix: rename?.fix ?? null,
152
+ terminalCli: terminalCliState(terminalCliAsk()),
147
153
  });
148
154
  }
149
155
 
@@ -421,10 +427,29 @@ async function awayUpdateTick() {
421
427
  return step.act;
422
428
  }
423
429
 
430
+ /** What terminal-cli-update.mjs is asked with: this deck, and the switch its
431
+ * own unattended update obeys. */
432
+ function terminalCliAsk() {
433
+ return { running: RUNNING_VERSION, pkgRoot: PKG_ROOT, enabled: heldPrefs.current()?.autoUpdate !== false };
434
+ }
435
+
436
+ /**
437
+ * The terminal's ccdeck, on the away-update's clock but not behind its gate:
438
+ * replacing that copy restarts nothing of the deck's, so neither a tab being
439
+ * looked at nor a deck without a launcher holds it back — only the boot grace,
440
+ * so that a start is never slowed by npm. terminal-cli-update.mjs decides
441
+ * whether, and starts it. Never throws: the next tick asks again.
442
+ */
443
+ function terminalCliTick() {
444
+ if (Date.now() - _bootedAt < AWAY_BOOT_GRACE_MS) return false;
445
+ try { return updateTerminalCli(terminalCliAsk()); } catch { return false; }
446
+ }
447
+
424
448
  /**
425
449
  * The away-update's clock. The boot grace counts from here, and the timer is
426
450
  * unref'd so it never keeps a process alive on its own. It does nothing until
427
- * the launcher has handed down a restart — see awayGate's `supervised`.
451
+ * the launcher has handed down a restart — see awayGate's `supervised` — except
452
+ * for the terminal's copy (terminalCliTick).
428
453
  *
429
454
  * Lifted out of startServer, which calls it once per boot; a second boot in the
430
455
  * same process replaces the timer rather than adding one.
@@ -432,7 +457,7 @@ async function awayUpdateTick() {
432
457
  function startAwayUpdate() {
433
458
  _bootedAt = Date.now();
434
459
  clearInterval(_awayTimer);
435
- _awayTimer = setInterval(() => { awayUpdateTick().catch(() => {}); }, AWAY_TICK_MS);
460
+ _awayTimer = setInterval(() => { awayUpdateTick().catch(() => {}); terminalCliTick(); }, AWAY_TICK_MS);
436
461
  _awayTimer.unref?.();
437
462
  }
438
463
 
@@ -81,12 +81,16 @@ export function deadLoginOf(row, { matches = false, signedInAt = null } = {}) {
81
81
  * No row, or one for somebody else, is read on the first pass. A struck row is
82
82
  * never read again, a row in backoff or claimed by another collector waits, and
83
83
  * otherwise it must be both older than the serve TTL and past its planned poll.
84
+ * A row held for another deck's reading (`cswap import-usage --hold`) is not
85
+ * read either, and that reading is trusted for the switch meanwhile.
84
86
  */
85
87
  export function collectionWouldRead(row, { matches = false, now }) {
86
88
  if (!matches || !row || typeof row !== "object") return true;
87
89
  if (Number(row.authDeadStrikes) >= 1) return false;
88
90
  const backoff = ms(row.backoffUntil);
89
91
  if (backoff != null && backoff > now) return false;
92
+ const held = ms(row.heldUntil);
93
+ if (held != null && held > now) return false;
90
94
  const claim = ms(row.claimUntil);
91
95
  if (claim != null && claim > now) return false;
92
96
  const fetched = ms(row.fetchedAt);