@commonlyai/cli 0.1.399 → 0.1.401
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/package.json +1 -1
- package/src/commands/agent.js +7 -0
- package/src/commands/daemon.js +39 -4
- package/src/lib/adapters/claude.js +158 -153
- package/src/lib/api.js +13 -0
- package/src/lib/daemon-lock.js +187 -0
- package/src/lib/daemon-service-windows.js +38 -11
- package/src/lib/daemon-supervisor.js +47 -5
- package/src/lib/turn-failure-notice.js +6 -0
package/package.json
CHANGED
package/src/commands/agent.js
CHANGED
|
@@ -2358,6 +2358,13 @@ export const performRun = ({
|
|
|
2358
2358
|
.then(() => revokeOrphansImpl({ client, log }))
|
|
2359
2359
|
.catch((err) => log(`spawn credential boot sweep failed (${err?.message ?? err})`));
|
|
2360
2360
|
|
|
2361
|
+
// F661: Commonly keeps no copy of a person's Claude login. A CLI before F661
|
|
2362
|
+
// left one in each Linux seat's state folder; this removes those, at their
|
|
2363
|
+
// exact paths only, once per process. Best-effort, like the sweep above.
|
|
2364
|
+
void Promise.resolve()
|
|
2365
|
+
.then(() => adapter?.removeLegacyLoginCopies?.())
|
|
2366
|
+
.catch((err) => log(`legacy login copy cleanup failed (${err?.message ?? err})`));
|
|
2367
|
+
|
|
2361
2368
|
// The bounds the server will clamp to. READ ONLY IF THERE IS AN ASK TO CLAMP:
|
|
2362
2369
|
// with no `COMMONLY_SPAWN_TTL_SECONDS` the cli sends no `ttlSeconds` at all
|
|
2363
2370
|
// and the server's default is what it is, so a per-run read would be a request
|
package/src/commands/daemon.js
CHANGED
|
@@ -45,6 +45,9 @@ import {
|
|
|
45
45
|
|
|
46
46
|
import { daemonLogsDir, daemonSeatLogPath, readLogTail } from '../lib/daemon-logs.js';
|
|
47
47
|
import { watchWindowsLauncher } from '../lib/daemon-service-windows.js';
|
|
48
|
+
import {
|
|
49
|
+
DAEMON_LOCK_EXIT, acquireDaemonLock, daemonLockPath, daemonLockWaitMs,
|
|
50
|
+
} from '../lib/daemon-lock.js';
|
|
48
51
|
import {
|
|
49
52
|
UNSANDBOXED_FLAG, clearUnsandboxedOptIn, hostSandboxReport, loadUnsandboxedOptIn, saveUnsandboxedOptIn, unsandboxedFlagRefusal,
|
|
50
53
|
} from '../lib/sandbox/windows-unsandboxed.js';
|
|
@@ -375,6 +378,7 @@ export const firstSupervisionPass = async ({
|
|
|
375
378
|
onLauncherGone,
|
|
376
379
|
isEnded = () => false,
|
|
377
380
|
armLauncherWatch = watchWindowsLauncher,
|
|
381
|
+
releaseLock = async () => {},
|
|
378
382
|
}) => {
|
|
379
383
|
let launcherGone = false;
|
|
380
384
|
armLauncherWatch({
|
|
@@ -385,9 +389,19 @@ export const firstSupervisionPass = async ({
|
|
|
385
389
|
});
|
|
386
390
|
const stopped = () => launcherGone || isEnded();
|
|
387
391
|
if (stopped()) return false;
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
392
|
+
try {
|
|
393
|
+
await supervisor.tick();
|
|
394
|
+
if (stopped()) return false;
|
|
395
|
+
await supervisor.heartbeat();
|
|
396
|
+
} catch (error) {
|
|
397
|
+
// F637 review: a throw here (a later seat's token read, say) comes after
|
|
398
|
+
// earlier seats have started. The caller's catch can't reach them or the
|
|
399
|
+
// lock, so stop them and free the lock before the error goes on, as the
|
|
400
|
+
// runtime-failure and shutdown paths do.
|
|
401
|
+
supervisor.stop();
|
|
402
|
+
await releaseLock();
|
|
403
|
+
throw error;
|
|
404
|
+
}
|
|
391
405
|
return !stopped();
|
|
392
406
|
};
|
|
393
407
|
|
|
@@ -727,6 +741,20 @@ Examples:
|
|
|
727
741
|
process.exitCode = process.platform === 'darwin' ? 0 : stopped.exitCode;
|
|
728
742
|
return;
|
|
729
743
|
}
|
|
744
|
+
// F637: one daemon per machine credential. Taken before the first
|
|
745
|
+
// request, so a refused copy never touches the server. It waits ~10 s
|
|
746
|
+
// first: a restart's old daemon is still exiting when the new one starts.
|
|
747
|
+
const lock = await acquireDaemonLock({
|
|
748
|
+
lockPath: daemonLockPath({ home: homedir() }),
|
|
749
|
+
waitMs: daemonLockWaitMs(),
|
|
750
|
+
});
|
|
751
|
+
if (!lock.ok) {
|
|
752
|
+
const holder = lock.holderPid ? `pid ${lock.holderPid}` : 'another process';
|
|
753
|
+
console.error(`${new Date().toISOString()} another Commonly daemon (${holder}) is already running for ${record.machineName}; this copy exits (${DAEMON_LOCK_EXIT}).`);
|
|
754
|
+
process.exitCode = DAEMON_LOCK_EXIT;
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
const releaseLock = () => { void lock.release(); };
|
|
730
758
|
const client = createClient({ instance: record.instanceUrl, token: record.daemonToken });
|
|
731
759
|
const logsDir = daemonLogsDir();
|
|
732
760
|
if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true });
|
|
@@ -775,6 +803,7 @@ Examples:
|
|
|
775
803
|
clearInterval(pollTimer);
|
|
776
804
|
clearInterval(heartbeatTimer);
|
|
777
805
|
supervisor.stop();
|
|
806
|
+
releaseLock();
|
|
778
807
|
// Without the marker launchd would restart forever. A successful
|
|
779
808
|
// exit parks it on macOS; systemd honors 77 directly.
|
|
780
809
|
process.exitCode = saved || process.platform !== 'darwin' ? 77 : 0;
|
|
@@ -825,6 +854,7 @@ Examples:
|
|
|
825
854
|
clearInterval(pollTimer);
|
|
826
855
|
clearInterval(heartbeatTimer);
|
|
827
856
|
supervisor.stop();
|
|
857
|
+
releaseLock();
|
|
828
858
|
process.exit(0);
|
|
829
859
|
};
|
|
830
860
|
// Under the Windows launcher, the launcher's exit is the stop
|
|
@@ -838,8 +868,12 @@ Examples:
|
|
|
838
868
|
shutdown();
|
|
839
869
|
},
|
|
840
870
|
isEnded: () => terminalEnded,
|
|
871
|
+
releaseLock: () => lock.release(),
|
|
841
872
|
});
|
|
842
|
-
if (!started)
|
|
873
|
+
if (!started) {
|
|
874
|
+
releaseLock();
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
843
877
|
const runtimeFailure = (error) => {
|
|
844
878
|
if (terminalEnded) return;
|
|
845
879
|
terminalEnded = true;
|
|
@@ -847,6 +881,7 @@ Examples:
|
|
|
847
881
|
clearInterval(pollTimer);
|
|
848
882
|
clearInterval(heartbeatTimer);
|
|
849
883
|
supervisor.stop();
|
|
884
|
+
releaseLock();
|
|
850
885
|
process.exitCode = 75;
|
|
851
886
|
};
|
|
852
887
|
pollTimer = setInterval(() => { void supervisor.tick().catch(runtimeFailure); }, Number(opts.poll) || DEFAULT_POLL_MS);
|
|
@@ -347,8 +347,8 @@ const STAGED_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{1
|
|
|
347
347
|
const isStagedCopyOf = (name) => (entry) => entry.startsWith(`.${name}.`) && entry.endsWith('.tmp')
|
|
348
348
|
&& STAGED_UUID.test(entry.slice(name.length + 2, -4));
|
|
349
349
|
|
|
350
|
-
// The login copy and any staged copy of it a failed or
|
|
351
|
-
// hold
|
|
350
|
+
// The login copy a CLI before F661 wrote, and any staged copy of it a failed or
|
|
351
|
+
// killed turn left: both hold an access token, and no current turn writes either.
|
|
352
352
|
const removeLoginCopy = async (configDir) => {
|
|
353
353
|
await removePrivateFile(configDir, '.credentials.json');
|
|
354
354
|
await removePrivateFile(configDir, '.credentials.json', { match: isStagedCopyOf('.credentials.json') });
|
|
@@ -472,120 +472,114 @@ export const loginRouteBaseUrl = (source = {}) => {
|
|
|
472
472
|
}
|
|
473
473
|
};
|
|
474
474
|
|
|
475
|
-
//
|
|
476
|
-
//
|
|
477
|
-
//
|
|
478
|
-
//
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
const
|
|
475
|
+
// F661: Commonly keeps no copy of a Claude login. Anthropic's terms let a
|
|
476
|
+
// person sign the unmodified `claude` binary in with their own subscription,
|
|
477
|
+
// and forbid a developer to collect, store or intermediate Claude.ai
|
|
478
|
+
// credentials, so nothing here reads ~/.claude/.credentials.json or writes a
|
|
479
|
+
// login file. Up to F661 a bwrap seat got an access-only copy of that file in
|
|
480
|
+
// its state folder (<state>/.claude/.credentials.json, staged beside it as
|
|
481
|
+
// .credentials.json.<uuid>.tmp) and a public seat registered its turns in
|
|
482
|
+
// <state>.login-turns so the last one could delete it. Those exact paths are
|
|
483
|
+
// what a previous CLI version may have left, and only they are removed.
|
|
484
|
+
const LEGACY_LOGIN_TURNS = '.login-turns';
|
|
485
|
+
// The marker name registerLoginTurn used: `<pid>-<uuid>`.
|
|
486
|
+
const LEGACY_TURN_MARKER = /^\d+-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
487
|
+
|
|
488
|
+
// Only Linux seats ever had a copy (bwrap has no keychain). On macOS a Seatbelt
|
|
489
|
+
// seat can write its whole state folder, so a confined child could swap
|
|
490
|
+
// `<seat>/.claude` for a link to the person's own ~/.claude between the host's
|
|
491
|
+
// check and its removal; nothing there is ours to delete, so nothing is.
|
|
492
|
+
// On Linux the host removes these paths outside any jail, and while a jail of
|
|
493
|
+
// the seat is live its .claude is a mount point the child cannot rename or
|
|
494
|
+
// replace (EBUSY), and `<seat>.login-turns` sits outside its writable bind.
|
|
495
|
+
const legacyCopiesPossible = (platform = process.platform) => platform === 'linux';
|
|
496
|
+
|
|
497
|
+
// The boot sweep and a turn's preparation can both clear the same seat's
|
|
498
|
+
// markers; when the other one removed the folder between this one's check and
|
|
499
|
+
// its read, the folder is already cleared, so that read is an empty list.
|
|
500
|
+
// Any other read failure still rejects.
|
|
501
|
+
export const readdirIfPresent = async (path, read = readdir) => {
|
|
487
502
|
try {
|
|
488
|
-
|
|
489
|
-
return true;
|
|
503
|
+
return await read(path);
|
|
490
504
|
} catch (err) {
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
};
|
|
494
|
-
const releaseLoginTurn = async (marker, loginPath) => {
|
|
495
|
-
await rm(marker, { force: true });
|
|
496
|
-
const dir = dirname(marker);
|
|
497
|
-
let others = [];
|
|
498
|
-
try {
|
|
499
|
-
others = await readdir(dir);
|
|
500
|
-
} catch { /* gone: nobody else is registered */ }
|
|
501
|
-
let live = 0;
|
|
502
|
-
for (const name of others) {
|
|
503
|
-
const pid = Number(name.split('-')[0]);
|
|
504
|
-
if (Number.isInteger(pid) && pid > 0 && pidAlive(pid)) live += 1;
|
|
505
|
-
else await rm(join(dir, name), { force: true });
|
|
506
|
-
}
|
|
507
|
-
if (!live) {
|
|
508
|
-
await removeLoginCopy(dirname(loginPath));
|
|
509
|
-
// Only an empty folder goes: a turn registering at this moment keeps it.
|
|
510
|
-
try { await rmdir(dir); } catch { /* not empty, or already gone */ }
|
|
505
|
+
if (err?.code === 'ENOENT') return [];
|
|
506
|
+
throw err;
|
|
511
507
|
}
|
|
512
508
|
};
|
|
513
509
|
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
//
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
// when its session check fails). A missing login removes the copy, so a person
|
|
523
|
-
// who logged out is not still signed in here.
|
|
524
|
-
const claudeLoginSource = (env) => join(
|
|
525
|
-
env?.CLAUDE_CONFIG_DIR || process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'),
|
|
526
|
-
'.credentials.json',
|
|
527
|
-
);
|
|
528
|
-
|
|
529
|
-
// Opened once, without following a symlink, and checked on the open handle,
|
|
530
|
-
// so the file read is the file checked (a FIFO cannot hold the open either).
|
|
531
|
-
// A public seat's copy (F96) holds the access token alone. Claude Code
|
|
532
|
-
// rotates the refresh token when it refreshes, so a jail holding one could
|
|
533
|
-
// spend it and leave the host signed out; without one it cannot refresh at
|
|
534
|
-
// all, so a login that would expire mid-turn is refused here instead.
|
|
535
|
-
// What a public seat's access-only login keeps: the token and the account
|
|
536
|
-
// metadata Claude Code reads beside it.
|
|
537
|
-
const ACCESS_ONLY_LOGIN_FIELDS = ['accessToken', 'expiresAt', 'scopes', 'subscriptionType', 'rateLimitTier'];
|
|
538
|
-
|
|
539
|
-
const accessOnlyLogin = (text, { source, mustOutlastMs, apiKeyHint = true }) => {
|
|
540
|
-
let login;
|
|
541
|
-
try {
|
|
542
|
-
login = JSON.parse(text);
|
|
543
|
-
} catch {
|
|
544
|
-
throw new Error(`refusing a Claude login that is not JSON: ${source}`);
|
|
545
|
-
}
|
|
546
|
-
const oauth = login?.claudeAiOauth;
|
|
547
|
-
if (!oauth || typeof oauth.accessToken !== 'string' || !oauth.accessToken) {
|
|
548
|
-
throw new Error(`refusing a Claude login with no access token: ${source}`);
|
|
510
|
+
const removeLegacyLoginTurns = async (statePath) => {
|
|
511
|
+
const turns = `${statePath}${LEGACY_LOGIN_TURNS}`;
|
|
512
|
+
const stat = await statOrNull(turns);
|
|
513
|
+
if (!stat) return;
|
|
514
|
+
// A link at the name is removed as a link, never followed.
|
|
515
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
516
|
+
await rm(turns, { force: true });
|
|
517
|
+
return;
|
|
549
518
|
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
519
|
+
// Its markers were empty files named `<pid>-<uuid>`; anything else in it is
|
|
520
|
+
// left, and so is the folder.
|
|
521
|
+
for (const name of await readdirIfPresent(turns)) {
|
|
522
|
+
if (!LEGACY_TURN_MARKER.test(name)) continue;
|
|
523
|
+
const entry = join(turns, name);
|
|
524
|
+
const entryStat = await statOrNull(entry);
|
|
525
|
+
if (entryStat?.isFile() && !entryStat.isSymbolicLink()) await rm(entry, { force: true });
|
|
555
526
|
}
|
|
556
|
-
|
|
557
|
-
// gains later, secret or not, never reaches the seat's writable HOME.
|
|
558
|
-
const access = Object.fromEntries(ACCESS_ONLY_LOGIN_FIELDS
|
|
559
|
-
.filter((field) => oauth[field] !== undefined)
|
|
560
|
-
.map((field) => [field, oauth[field]]));
|
|
561
|
-
return `${JSON.stringify({ claudeAiOauth: access })}\n`;
|
|
527
|
+
try { await rmdir(turns); } catch { /* not empty: not ours to clear */ }
|
|
562
528
|
};
|
|
563
529
|
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
530
|
+
/**
|
|
531
|
+
* Removes every login copy a CLI before F661 left under the Claude seat state
|
|
532
|
+
* root (~/.commonly/claude-homes): `<seat>/.claude/.credentials.json`, its
|
|
533
|
+
* staged copies, and the `<seat>.login-turns` markers. Nothing else in a seat
|
|
534
|
+
* folder, and nothing outside the root, is touched. Run once per seat process.
|
|
535
|
+
* Linux only: off Linux it returns before touching the filesystem at all.
|
|
536
|
+
*/
|
|
537
|
+
export const removeLegacyClaudeLoginCopies = async (opts = {}) => {
|
|
538
|
+
if (!legacyCopiesPossible(opts.platform || process.platform)) return;
|
|
539
|
+
const root = opts.root || dirname(publicClaudeStateRoot('x'));
|
|
540
|
+
const rootStat = await statOrNull(root);
|
|
541
|
+
if (!rootStat || rootStat.isSymbolicLink() || !rootStat.isDirectory()) return;
|
|
542
|
+
for (const name of await readdir(root)) {
|
|
543
|
+
const entry = join(root, name);
|
|
544
|
+
if (name.endsWith(LEGACY_LOGIN_TURNS)) {
|
|
545
|
+
await removeLegacyLoginTurns(entry.slice(0, -LEGACY_LOGIN_TURNS.length));
|
|
546
|
+
continue;
|
|
574
547
|
}
|
|
575
|
-
|
|
576
|
-
|
|
548
|
+
const stat = await statOrNull(entry);
|
|
549
|
+
if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) continue;
|
|
550
|
+
await removeLoginCopy(join(entry, '.claude'));
|
|
577
551
|
}
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
552
|
+
};
|
|
553
|
+
|
|
554
|
+
// A bwrap workspace seat signs in with the person's own long-lived token from
|
|
555
|
+
// `claude setup-token`, which they export as CLAUDE_CODE_OAUTH_TOKEN for the
|
|
556
|
+
// agent. Claude Code reads it from its environment; Commonly passes the value
|
|
557
|
+
// through to the jail and writes it nowhere.
|
|
558
|
+
// F661: what a Linux workspace seat with neither its own token nor a key is
|
|
559
|
+
// told. A seat the daemon runs (COMMONLY_MANAGED_RUNNER, set on every child it
|
|
560
|
+
// spawns) can't get either: the service carries only the provider keys
|
|
561
|
+
// adapters declare, and Commonly never writes a token or key into the service
|
|
562
|
+
// file. So it is sent to a foreground `agent run`, as F171 does for keys.
|
|
563
|
+
const WORKSPACE_LOGIN_PREFIX = 'workspace Claude agents on Linux need your own Claude token or an API key';
|
|
564
|
+
const workspaceLoginRefusal = (ctx) => {
|
|
565
|
+
const managed = (ctx.env || process.env).COMMONLY_MANAGED_RUNNER === '1'
|
|
566
|
+
|| process.env.COMMONLY_MANAGED_RUNNER === '1';
|
|
567
|
+
if (managed) {
|
|
568
|
+
return new Error(`${WORKSPACE_LOGIN_PREFIX}, and this agent runs under the background daemon, which carries `
|
|
569
|
+
+ 'neither: Commonly never writes your token or key into its service file. Run it with '
|
|
570
|
+
+ `\`${CLI} agent run ${ctx.seatKey || ctx.agentName || '<name>'}\` from a shell where you have exported `
|
|
571
|
+
+ 'CLAUDE_CODE_OAUTH_TOKEN (from `claude setup-token`) or ANTHROPIC_API_KEY.');
|
|
586
572
|
}
|
|
573
|
+
return new Error(`${WORKSPACE_LOGIN_PREFIX}: run \`claude setup-token\` in your own terminal on this machine `
|
|
574
|
+
+ 'and set CLAUDE_CODE_OAUTH_TOKEN to it in the agent\'s environment, or set ANTHROPIC_API_KEY (it stays on '
|
|
575
|
+
+ 'this computer behind a per-turn proxy). Commonly passes your token to Claude Code and keeps no copy.');
|
|
587
576
|
};
|
|
588
577
|
|
|
578
|
+
const ownClaudeToken = (source = {}) => (
|
|
579
|
+
typeof source.CLAUDE_CODE_OAUTH_TOKEN === 'string' && source.CLAUDE_CODE_OAUTH_TOKEN.trim()
|
|
580
|
+
? source.CLAUDE_CODE_OAUTH_TOKEN : null
|
|
581
|
+
);
|
|
582
|
+
|
|
589
583
|
// The per-seat folder a bwrap seat runs in. A public seat (F96) gets its own,
|
|
590
584
|
// never the workspace seat's: that one holds the transcripts of private-pod
|
|
591
585
|
// turns, and the same agent can run both kinds of
|
|
@@ -598,30 +592,24 @@ export const bwrapClaudeStatePath = (ctx, seat = 'workspace') => {
|
|
|
598
592
|
};
|
|
599
593
|
|
|
600
594
|
// State for a seat under bwrap, outside the person's project, with the auth
|
|
601
|
-
// metadata whitelist and
|
|
602
|
-
// and makes it HOME, so transcripts land here rather than in the project.
|
|
603
|
-
//
|
|
604
|
-
|
|
605
|
-
const prepareWorkspaceBwrapClaudeState = async (ctx, { login = 'carry', seat = 'workspace' } = {}) => {
|
|
595
|
+
// metadata whitelist and no login (F661). The jail binds this folder writable
|
|
596
|
+
// and makes it HOME, so transcripts land here rather than in the project. A
|
|
597
|
+
// login copy or turn marker an older CLI left for this seat is removed first.
|
|
598
|
+
const prepareWorkspaceBwrapClaudeState = async (ctx, { seat = 'workspace' } = {}) => {
|
|
606
599
|
const statePath = bwrapClaudeStatePath(ctx, seat);
|
|
607
600
|
const tmpPath = join(statePath, 'tmp');
|
|
608
601
|
const configDir = join(statePath, '.claude');
|
|
609
602
|
await ensureStateFolder(statePath);
|
|
610
603
|
for (const dir of [tmpPath, configDir]) await ensurePrivateDir(dir);
|
|
604
|
+
if (legacyCopiesPossible(ctx._platform || process.platform)) {
|
|
605
|
+
await removeLoginCopy(configDir);
|
|
606
|
+
await removeLegacyLoginTurns(statePath);
|
|
607
|
+
}
|
|
611
608
|
|
|
612
609
|
const configPath = await replacePrivateFile(
|
|
613
610
|
statePath, '.claude.json', `${JSON.stringify(await claudeAuthMetadata(), null, 2)}\n`,
|
|
614
611
|
);
|
|
615
|
-
|
|
616
|
-
await removeLoginCopy(configDir);
|
|
617
|
-
return { statePath, tmpPath, configPath, loginPath: null };
|
|
618
|
-
}
|
|
619
|
-
const loginPath = await carryClaudeLogin(ctx.env, configDir, login === 'access-only'
|
|
620
|
-
// A workspace seat's jail never sees the host's API key, so only a public
|
|
621
|
-
// seat is told to set one.
|
|
622
|
-
? { accessOnly: true, mustOutlastMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS, apiKeyHint: seat === 'public' }
|
|
623
|
-
: {});
|
|
624
|
-
return { statePath, tmpPath, configPath, loginPath };
|
|
612
|
+
return { statePath, tmpPath, configPath };
|
|
625
613
|
};
|
|
626
614
|
|
|
627
615
|
const buildClaudeEnv = (input, state, expansionEnv = {}, credentialFile = null, publicSeat = false, platform = process.platform) => {
|
|
@@ -1889,6 +1877,9 @@ const prepareArgv = async (innerArgv, ctx) => {
|
|
|
1889
1877
|
export default {
|
|
1890
1878
|
get requiresModel() { return seatModelRequired(); },
|
|
1891
1879
|
name: 'claude',
|
|
1880
|
+
// F661: run once when a seat process starts; removes login copies an older
|
|
1881
|
+
// CLI left under ~/.commonly/claude-homes, at their exact paths only.
|
|
1882
|
+
removeLegacyLoginCopies: () => removeLegacyClaudeLoginCopies(),
|
|
1892
1883
|
// Identity-bearing runtime tag written into AgentInstallation.config.runtime
|
|
1893
1884
|
// by `commonly agent attach`. The CLI command stays `commonly agent attach
|
|
1894
1885
|
// claude` (ergonomic) but the persisted runtimeType matches AGENT_TYPES so
|
|
@@ -2062,7 +2053,9 @@ export default {
|
|
|
2062
2053
|
let providerProxy = null;
|
|
2063
2054
|
// A login seat's gateway, when the host names one: config, not a secret.
|
|
2064
2055
|
let publicLoginBaseUrl = null;
|
|
2065
|
-
|
|
2056
|
+
// F661: a workspace bwrap seat's own CLAUDE_CODE_OAUTH_TOKEN, passed
|
|
2057
|
+
// through to the jail's environment and written nowhere.
|
|
2058
|
+
let ownLoginToken = null;
|
|
2066
2059
|
let publicSkillArgs = [];
|
|
2067
2060
|
// No jail to prepare for on a policy-only Windows host.
|
|
2068
2061
|
const jailed = !policyOnlyHost(ctx);
|
|
@@ -2088,12 +2081,14 @@ export default {
|
|
|
2088
2081
|
if (providerProxy) {
|
|
2089
2082
|
return Object.assign(env, { ANTHROPIC_BASE_URL: providerProxy.baseURL, ANTHROPIC_API_KEY: providerProxy.token });
|
|
2090
2083
|
}
|
|
2084
|
+
if (ownLoginToken) Object.assign(env, { CLAUDE_CODE_OAUTH_TOKEN: ownLoginToken });
|
|
2091
2085
|
return publicLoginBaseUrl ? Object.assign(env, { ANTHROPIC_BASE_URL: publicLoginBaseUrl }) : env;
|
|
2092
2086
|
};
|
|
2093
|
-
// The values a failure tail or reply must never echo: the seat's own,
|
|
2094
|
-
//
|
|
2087
|
+
// The values a failure tail or reply must never echo: the seat's own, the
|
|
2088
|
+
// per-turn proxy token the child was handed in place of the host key, and
|
|
2089
|
+
// the person's own Claude token.
|
|
2095
2090
|
const turnCredentials = (spawnContext) => [
|
|
2096
|
-
...spawnCredentials(spawnContext), providerProxy?.token,
|
|
2091
|
+
...spawnCredentials(spawnContext), providerProxy?.token, ownLoginToken,
|
|
2097
2092
|
].filter(Boolean);
|
|
2098
2093
|
try {
|
|
2099
2094
|
// Checked (and recorded, the first time) before the state is prepared
|
|
@@ -2164,21 +2159,42 @@ export default {
|
|
|
2164
2159
|
}
|
|
2165
2160
|
} else if (workspaceBwrapSandbox) {
|
|
2166
2161
|
// Checked before the state is prepared, so a host that cannot run the
|
|
2167
|
-
// jail
|
|
2162
|
+
// jail gets no state folder.
|
|
2168
2163
|
const bwrap = (ctx._detectBwrap || detectBwrap)();
|
|
2169
2164
|
if (!bwrap.available) throw new Error(`workspace Claude agents require bwrap: ${bwrap.error}`);
|
|
2170
2165
|
const { claudeBin, claudeInstall } = resolveClaudeInstall(withClaudePath(ctx.env));
|
|
2171
2166
|
if (!claudeInstall) throw claudeInstallRefusal(claudeBin);
|
|
2172
|
-
|
|
2173
|
-
//
|
|
2174
|
-
|
|
2167
|
+
// F661: the jail's HOME is the seat's own folder, which holds no login.
|
|
2168
|
+
// Claude Code signs in there with the person's own token, from their
|
|
2169
|
+
// environment; Commonly never reads or copies ~/.claude/.credentials.json.
|
|
2170
|
+
// An API key is the other way in, kept on the host behind a per-turn
|
|
2171
|
+
// proxy as on a public seat. The token wins when both are set.
|
|
2172
|
+
const source = ctx.env || process.env;
|
|
2173
|
+
ownLoginToken = ownClaudeToken(source);
|
|
2174
|
+
if (!ownLoginToken && !source.ANTHROPIC_API_KEY) throw workspaceLoginRefusal(ctx);
|
|
2175
|
+
if (!ownLoginToken && ctx.environment?.sandbox?.network?.policy === 'restricted') {
|
|
2176
|
+
throw new Error('workspace Claude agents on Linux on an API key need shared bwrap networking to reach '
|
|
2177
|
+
+ 'the key\'s proxy; sandbox.network.policy "restricted" cuts it off.');
|
|
2178
|
+
}
|
|
2179
|
+
publicClaudeState = await prepareWorkspaceBwrapClaudeState(ctx);
|
|
2180
|
+
if (ownLoginToken) {
|
|
2181
|
+
// The host's model route, when it is the one the login uses.
|
|
2182
|
+
publicLoginBaseUrl = loginRouteBaseUrl(source);
|
|
2183
|
+
} else {
|
|
2184
|
+
providerProxy = await (ctx._startProviderProxy || startProviderProxy)({
|
|
2185
|
+
provider: { baseURL: source.ANTHROPIC_BASE_URL || 'https://api.anthropic.com' },
|
|
2186
|
+
keyMaterial: source.ANTHROPIC_API_KEY,
|
|
2187
|
+
wire: 'anthropic-messages',
|
|
2188
|
+
adapterLabel: 'Claude',
|
|
2189
|
+
});
|
|
2190
|
+
}
|
|
2175
2191
|
} else if (publicBwrapSandbox) {
|
|
2176
|
-
// F96: the workspace tier's jail
|
|
2177
|
-
//
|
|
2178
|
-
//
|
|
2179
|
-
//
|
|
2180
|
-
//
|
|
2181
|
-
// seat is refused before a proxy starts
|
|
2192
|
+
// F96: the workspace tier's jail. Since F661 it reaches the model only
|
|
2193
|
+
// on an API key, which stays on the host behind a per-turn proxy:
|
|
2194
|
+
// strangers drive this seat, so it never runs on the person's own
|
|
2195
|
+
// Claude subscription, and Commonly holds no copy of their login. The
|
|
2196
|
+
// model is across the network: restricted networking (--unshare-net)
|
|
2197
|
+
// cuts off the host proxy, so the seat is refused before a proxy starts.
|
|
2182
2198
|
if (ctx.environment?.sandbox?.network?.policy === 'restricted') {
|
|
2183
2199
|
throw new Error('public Claude agents on Linux need shared bwrap networking to reach the model; '
|
|
2184
2200
|
+ 'sandbox.network.policy "restricted" cuts it off.');
|
|
@@ -2196,23 +2212,18 @@ export default {
|
|
|
2196
2212
|
const { claudeBin, claudeInstall } = resolveClaudeInstall(withClaudePath(ctx.env));
|
|
2197
2213
|
if (!claudeInstall) throw claudeInstallRefusal(claudeBin);
|
|
2198
2214
|
const source = ctx.env || process.env;
|
|
2199
|
-
if (source.ANTHROPIC_API_KEY) {
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
keyMaterial: source.ANTHROPIC_API_KEY,
|
|
2204
|
-
wire: 'anthropic-messages',
|
|
2205
|
-
adapterLabel: 'Claude',
|
|
2206
|
-
});
|
|
2207
|
-
} else {
|
|
2208
|
-
publicClaudeState = await prepareWorkspaceBwrapClaudeState(ctx, { login: 'access-only', seat: 'public' });
|
|
2209
|
-
publicLoginBaseUrl = loginRouteBaseUrl(source);
|
|
2210
|
-
if (!publicClaudeState.loginPath) {
|
|
2211
|
-
throw new Error('public Claude agents on Linux need ANTHROPIC_API_KEY in the agent\'s environment, '
|
|
2212
|
-
+ 'or sign in with `claude` on this machine first.');
|
|
2213
|
-
}
|
|
2214
|
-
loginTurn = await registerLoginTurn(publicClaudeState.statePath);
|
|
2215
|
+
if (!source.ANTHROPIC_API_KEY) {
|
|
2216
|
+
throw new Error('public Claude agents on Linux need ANTHROPIC_API_KEY in the agent\'s environment. '
|
|
2217
|
+
+ 'Strangers can drive a public agent, so it never runs on your own Claude login; the key stays on '
|
|
2218
|
+
+ 'this computer and the agent gets a per-turn proxy token.');
|
|
2215
2219
|
}
|
|
2220
|
+
publicClaudeState = await prepareWorkspaceBwrapClaudeState(ctx, { seat: 'public' });
|
|
2221
|
+
providerProxy = await (ctx._startProviderProxy || startProviderProxy)({
|
|
2222
|
+
provider: { baseURL: source.ANTHROPIC_BASE_URL || 'https://api.anthropic.com' },
|
|
2223
|
+
keyMaterial: source.ANTHROPIC_API_KEY,
|
|
2224
|
+
wire: 'anthropic-messages',
|
|
2225
|
+
adapterLabel: 'Claude',
|
|
2226
|
+
});
|
|
2216
2227
|
}
|
|
2217
2228
|
if (publicTrust) {
|
|
2218
2229
|
const prompt = await publicSkillPromptArgs(mountedSkills, seatPermissionsText({
|
|
@@ -2469,12 +2480,6 @@ export default {
|
|
|
2469
2480
|
}
|
|
2470
2481
|
try { await providerProxy?.close(); } catch { /* ignore */ }
|
|
2471
2482
|
try { await microvm?.close?.(); } catch { /* ignore */ }
|
|
2472
|
-
// A public seat's login copy lives for its turns (F96): the last live
|
|
2473
|
-
// turn of the agent to finish removes it.
|
|
2474
|
-
if (publicBwrapSandbox && !workspaceBwrapSandbox && publicClaudeState?.loginPath) {
|
|
2475
|
-
if (loginTurn) await releaseLoginTurn(loginTurn, publicClaudeState.loginPath);
|
|
2476
|
-
else await removeLoginCopy(dirname(publicClaudeState.loginPath));
|
|
2477
|
-
}
|
|
2478
2483
|
}
|
|
2479
2484
|
},
|
|
2480
2485
|
};
|
package/src/lib/api.js
CHANGED
|
@@ -38,6 +38,17 @@ const summarizeTextError = (text, status) => {
|
|
|
38
38
|
return line.length > MAX_TEXT_ERROR ? `${line.slice(0, MAX_TEXT_ERROR)}…` : line;
|
|
39
39
|
};
|
|
40
40
|
|
|
41
|
+
// F637: a 429's Retry-After, in ms, from delta-seconds or an HTTP date (RFC
|
|
42
|
+
// 9110 10.2.3). A date already past is 0; anything unreadable is undefined.
|
|
43
|
+
export const parseRetryAfterMs = (value, nowMs = Date.now()) => {
|
|
44
|
+
const text = String(value ?? '').trim();
|
|
45
|
+
if (!text) return undefined;
|
|
46
|
+
if (/^\d+$/.test(text)) return Number(text) * 1000;
|
|
47
|
+
if (/^[+-]?\d/.test(text)) return undefined;
|
|
48
|
+
const at = Date.parse(text);
|
|
49
|
+
return Number.isNaN(at) ? undefined : Math.max(0, at - nowMs);
|
|
50
|
+
};
|
|
51
|
+
|
|
41
52
|
const handleResponse = async (res, session = null) => {
|
|
42
53
|
const text = await res.text();
|
|
43
54
|
let body;
|
|
@@ -53,6 +64,8 @@ const handleResponse = async (res, session = null) => {
|
|
|
53
64
|
const err = new Error(msg);
|
|
54
65
|
err.status = res.status;
|
|
55
66
|
err.body = body;
|
|
67
|
+
const retryAfterMs = parseRetryAfterMs(res.headers?.get?.('retry-after'));
|
|
68
|
+
if (retryAfterMs !== undefined) err.retryAfterMs = retryAfterMs;
|
|
56
69
|
throw err;
|
|
57
70
|
}
|
|
58
71
|
return body;
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One `commonly daemon run` per machine credential (F637).
|
|
3
|
+
*
|
|
4
|
+
* A Windows install piled up ~140 daemons on one key, each polling the server
|
|
5
|
+
* on its own 30 s timers, and nothing refused the second copy. The lock is a
|
|
6
|
+
* listening local socket: a named pipe on Windows, a unix socket under
|
|
7
|
+
* ~/.commonly/daemon elsewhere. The OS frees it when the holder dies, however
|
|
8
|
+
* it dies, so it never goes stale the way a pid file does (and a reused pid
|
|
9
|
+
* can never pass for the holder).
|
|
10
|
+
*
|
|
11
|
+
* The holder answers anyone who connects with one JSON line, `{"pid":<n>}`,
|
|
12
|
+
* and hangs up, so a refused daemon can name the copy that is already running.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createHash } from 'crypto';
|
|
16
|
+
import { existsSync, mkdirSync, unlinkSync } from 'fs';
|
|
17
|
+
import { createConnection, createServer } from 'net';
|
|
18
|
+
import { dirname, join } from 'path';
|
|
19
|
+
|
|
20
|
+
// The exit code of a daemon that found another one holding the lock. The
|
|
21
|
+
// Windows launcher waits on it and tries again; it never disables the task.
|
|
22
|
+
export const DAEMON_LOCK_EXIT = 79;
|
|
23
|
+
|
|
24
|
+
// A restart's old node exits within ~2 s of its launcher ending, so a new
|
|
25
|
+
// daemon waits this long before it gives up.
|
|
26
|
+
export const DAEMON_LOCK_WAIT_MS = 10_000;
|
|
27
|
+
const RETRY_EVERY_MS = 500;
|
|
28
|
+
const PID_READ_TIMEOUT_MS = 1_000;
|
|
29
|
+
|
|
30
|
+
// A unix socket path is capped near 104 bytes on macOS (108 on Linux).
|
|
31
|
+
const MAX_SOCKET_PATH = 100;
|
|
32
|
+
|
|
33
|
+
// Keyed by the home alone. A home holds exactly one machine record
|
|
34
|
+
// (~/.commonly/daemon/machine.json), and `daemon run --instance` refuses any
|
|
35
|
+
// instance but the registered one, so one daemon per home is the rule. Keying
|
|
36
|
+
// by machineDbId would let an old daemon still running across a
|
|
37
|
+
// `daemon register` (a new machineDbId) sit beside the new one.
|
|
38
|
+
export const daemonLockId = ({ home }) => createHash('sha256')
|
|
39
|
+
.update(String(home))
|
|
40
|
+
.digest('hex')
|
|
41
|
+
.slice(0, 16);
|
|
42
|
+
|
|
43
|
+
export const daemonLockPath = ({ home, platform = process.platform }) => {
|
|
44
|
+
const id = daemonLockId({ home });
|
|
45
|
+
if (platform === 'win32') return `\\\\.\\pipe\\commonly-daemon-${id}`;
|
|
46
|
+
const path = join(home, '.commonly', 'daemon', `daemon-${id}.sock`);
|
|
47
|
+
// A home too deep for a socket path falls back to /tmp; the id still
|
|
48
|
+
// carries the home, so two accounts never share one.
|
|
49
|
+
return Buffer.byteLength(path) <= MAX_SOCKET_PATH ? path : join('/tmp', `commonly-daemon-${id}.sock`);
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const isPipe = (lockPath) => lockPath.startsWith('\\\\.\\pipe\\');
|
|
53
|
+
|
|
54
|
+
const listen = (server, lockPath) => new Promise((resolve, reject) => {
|
|
55
|
+
const onError = (error) => { server.off('listening', onListening); reject(error); };
|
|
56
|
+
const onListening = () => { server.off('error', onError); resolve(); };
|
|
57
|
+
server.once('error', onError);
|
|
58
|
+
server.once('listening', onListening);
|
|
59
|
+
server.listen(lockPath);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// Connect to whoever holds the path. `held` with the pid it sent (null when it
|
|
63
|
+
// sent nothing readable in time), or `free` when nothing is listening there.
|
|
64
|
+
const probe = (lockPath) => new Promise((resolve) => {
|
|
65
|
+
let settled = false;
|
|
66
|
+
let data = '';
|
|
67
|
+
const finish = (result) => {
|
|
68
|
+
if (settled) return;
|
|
69
|
+
settled = true;
|
|
70
|
+
clearTimeout(timer);
|
|
71
|
+
socket.destroy();
|
|
72
|
+
resolve(result);
|
|
73
|
+
};
|
|
74
|
+
const socket = createConnection(lockPath);
|
|
75
|
+
const timer = setTimeout(() => finish({ state: 'held', holderPid: null }), PID_READ_TIMEOUT_MS);
|
|
76
|
+
const parsePid = () => {
|
|
77
|
+
try {
|
|
78
|
+
const pid = JSON.parse(data.split('\n')[0])?.pid;
|
|
79
|
+
return Number.isInteger(pid) ? pid : null;
|
|
80
|
+
} catch {
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
socket.setEncoding('utf8');
|
|
85
|
+
socket.on('data', (chunk) => {
|
|
86
|
+
data += chunk;
|
|
87
|
+
if (data.includes('\n')) finish({ state: 'held', holderPid: parsePid() });
|
|
88
|
+
});
|
|
89
|
+
socket.on('end', () => finish({ state: 'held', holderPid: parsePid() }));
|
|
90
|
+
socket.on('error', (error) => {
|
|
91
|
+
if (error.code === 'ECONNREFUSED' || error.code === 'ENOENT') finish({ state: 'free' });
|
|
92
|
+
else finish({ state: 'held', holderPid: parsePid() });
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
const holderServer = () => {
|
|
97
|
+
const server = createServer((socket) => {
|
|
98
|
+
socket.on('error', () => {});
|
|
99
|
+
socket.end(`${JSON.stringify({ pid: process.pid })}\n`);
|
|
100
|
+
});
|
|
101
|
+
// A late client error must never end the daemon.
|
|
102
|
+
server.on('error', () => {});
|
|
103
|
+
return server;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const held = (server, lockPath) => {
|
|
107
|
+
// The lock never keeps the process alive on its own.
|
|
108
|
+
server.unref();
|
|
109
|
+
let released = false;
|
|
110
|
+
const unlinkOwn = () => {
|
|
111
|
+
if (isPipe(lockPath)) return;
|
|
112
|
+
try { unlinkSync(lockPath); } catch { /* already gone */ }
|
|
113
|
+
};
|
|
114
|
+
// process.exit() skips the close below; the socket file goes with the exit.
|
|
115
|
+
const onExit = () => { if (!released) unlinkOwn(); };
|
|
116
|
+
process.once('exit', onExit);
|
|
117
|
+
const release = () => new Promise((resolve) => {
|
|
118
|
+
if (released) { resolve(); return; }
|
|
119
|
+
released = true;
|
|
120
|
+
process.off('exit', onExit);
|
|
121
|
+
// close() unlinks a unix socket server's path itself (libuv's
|
|
122
|
+
// uv__pipe_close, synchronously inside the call), so no unlink of our own
|
|
123
|
+
// here: a second one could remove the socket of a daemon that bound in
|
|
124
|
+
// between. The exit hook above covers exits that skip release.
|
|
125
|
+
server.close(() => resolve());
|
|
126
|
+
});
|
|
127
|
+
return { ok: true, lockPath, release };
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* One attempt: `{ ok: true, release }` when this process now holds the lock,
|
|
132
|
+
* `{ ok: false, holderPid }` when another process does.
|
|
133
|
+
*/
|
|
134
|
+
export const tryAcquireDaemonLock = async ({ lockPath }) => {
|
|
135
|
+
if (!isPipe(lockPath)) {
|
|
136
|
+
const dir = dirname(lockPath);
|
|
137
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
138
|
+
}
|
|
139
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
140
|
+
const server = holderServer();
|
|
141
|
+
try {
|
|
142
|
+
// eslint-disable-next-line no-await-in-loop
|
|
143
|
+
await listen(server, lockPath);
|
|
144
|
+
return held(server, lockPath);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (error.code !== 'EADDRINUSE') throw error;
|
|
147
|
+
}
|
|
148
|
+
// eslint-disable-next-line no-await-in-loop
|
|
149
|
+
const found = await probe(lockPath);
|
|
150
|
+
if (found.state === 'held') return { ok: false, holderPid: found.holderPid };
|
|
151
|
+
// Nothing answers: a socket file a killed holder left behind. A pipe is
|
|
152
|
+
// freed by the OS, so on Windows this is only a holder that just exited.
|
|
153
|
+
// Accepted race: two copies that probe the same stale socket within the
|
|
154
|
+
// same few microseconds can both unlink and both bind. POSIX service
|
|
155
|
+
// managers (launchd, systemd) already run one copy, so this needs two
|
|
156
|
+
// hand-started daemons racing a crashed one; Windows pipes can't hit it.
|
|
157
|
+
if (attempt === 0 && !isPipe(lockPath)) {
|
|
158
|
+
try { unlinkSync(lockPath); } catch { /* raced with another reclaim */ }
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return { ok: false, holderPid: null };
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const pause = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Retries for `waitMs`, so the daemon of a restart can take over from the old
|
|
168
|
+
* one that is still exiting. Never makes a request to the server.
|
|
169
|
+
*/
|
|
170
|
+
export const acquireDaemonLock = async ({
|
|
171
|
+
lockPath, waitMs = DAEMON_LOCK_WAIT_MS, retryEveryMs = RETRY_EVERY_MS, now = Date.now, sleep = pause,
|
|
172
|
+
}) => {
|
|
173
|
+
const deadline = now() + waitMs;
|
|
174
|
+
for (;;) {
|
|
175
|
+
// eslint-disable-next-line no-await-in-loop
|
|
176
|
+
const result = await tryAcquireDaemonLock({ lockPath });
|
|
177
|
+
if (result.ok || now() >= deadline) return result;
|
|
178
|
+
// eslint-disable-next-line no-await-in-loop
|
|
179
|
+
await sleep(Math.min(retryEveryMs, Math.max(0, deadline - now())));
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
// COMMONLY_DAEMON_LOCK_WAIT_MS shortens the wait (tests); bad values keep the default.
|
|
184
|
+
export const daemonLockWaitMs = (env = process.env) => {
|
|
185
|
+
const value = Number(env.COMMONLY_DAEMON_LOCK_WAIT_MS);
|
|
186
|
+
return Number.isFinite(value) && value >= 0 ? value : DAEMON_LOCK_WAIT_MS;
|
|
187
|
+
};
|
|
@@ -16,6 +16,9 @@
|
|
|
16
16
|
* - A one-minute repeating trigger with `IgnoreNew` is the watchdog for the
|
|
17
17
|
* launcher itself: while the task runs it starts nothing, and if the
|
|
18
18
|
* launcher is killed the next minute brings it back.
|
|
19
|
+
* - Exit 79 means another daemon already holds this machine's lock (F637):
|
|
20
|
+
* the launcher waits 30 s and tries again, so the task stays running and
|
|
21
|
+
* takes over when the holder dies. It never disables the task for it.
|
|
19
22
|
* - On 77/78 the launcher disables the task before it exits, so the watchdog
|
|
20
23
|
* does not restart a daemon that has been told to stop. That is launchd's
|
|
21
24
|
* "park on a successful exit" in Task Scheduler's terms; `daemon start` and
|
|
@@ -60,7 +63,8 @@ export const psQuote = (value) => `'${String(value).replace(/['‘’‚‛]/g,
|
|
|
60
63
|
|
|
61
64
|
export const windowsLauncherScript = ({ nodePath, cliPath, logPath, envFile, taskName = WINDOWS_TASK_NAME }) => `# Commonly daemon launcher. Written by \`commonly daemon install\`; re-run that command instead of editing this file.
|
|
62
65
|
# It loads the service environment, then keeps \`commonly daemon run\` alive: every exit restarts it after 5 s,
|
|
63
|
-
# except 77 (this computer's key was revoked) and 78 (no valid local registration), which disable the task and stop
|
|
66
|
+
# except 77 (this computer's key was revoked) and 78 (no valid local registration), which disable the task and stop,
|
|
67
|
+
# and 79 (another daemon already runs for this computer), which waits 30 s and tries again.
|
|
64
68
|
$ErrorActionPreference = 'Continue'
|
|
65
69
|
$node = ${psQuote(nodePath)}
|
|
66
70
|
$cli = ${psQuote(cliPath)}
|
|
@@ -80,6 +84,7 @@ $env:COMMONLY_DAEMON_LAUNCHER_PID = "$PID"
|
|
|
80
84
|
while ($true) {
|
|
81
85
|
& $node $cli daemon run --foreground 2>&1 | ForEach-Object { "$_" } | Add-Content -LiteralPath $log -Encoding UTF8
|
|
82
86
|
$code = $LASTEXITCODE
|
|
87
|
+
if ($code -eq 79) { Start-Sleep -Seconds 30; continue }
|
|
83
88
|
if ($code -eq 77 -or $code -eq 78) {
|
|
84
89
|
& schtasks.exe /Change /TN $task /DISABLE | Out-Null
|
|
85
90
|
if ($LASTEXITCODE -eq 0) { exit $code }
|
|
@@ -187,15 +192,23 @@ export const installWindowsService = async ({
|
|
|
187
192
|
|
|
188
193
|
export const LAUNCHER_PID_ENV = 'COMMONLY_DAEMON_LAUNCHER_PID';
|
|
189
194
|
|
|
190
|
-
|
|
195
|
+
// F637: EPERM counts as gone. The real launcher runs as this same user at
|
|
196
|
+
// LeastPrivilege, so this process may always signal it; EPERM means the pid
|
|
197
|
+
// now belongs to another account's (or an elevated) process, i.e. the launcher
|
|
198
|
+
// exited and Windows reused its pid. Read as "alive", that kept an orphaned
|
|
199
|
+
// daemon polling forever.
|
|
200
|
+
export const launcherPidAlive = (pid, kill = process.kill.bind(process)) => {
|
|
191
201
|
try {
|
|
192
|
-
|
|
202
|
+
kill(pid, 0);
|
|
193
203
|
return true;
|
|
194
|
-
} catch
|
|
195
|
-
return
|
|
204
|
+
} catch {
|
|
205
|
+
return false;
|
|
196
206
|
}
|
|
197
207
|
};
|
|
198
208
|
|
|
209
|
+
// A write into the pipe of a launcher that has exited.
|
|
210
|
+
const PIPE_GONE = new Set(['EPIPE', 'ERR_STREAM_DESTROYED']);
|
|
211
|
+
|
|
199
212
|
/**
|
|
200
213
|
* `schtasks /End` terminates the launcher only; the node it started would
|
|
201
214
|
* keep running, unsupervised and invisible to the task (seen on windows-latest,
|
|
@@ -207,7 +220,7 @@ const pidAlive = (pid) => {
|
|
|
207
220
|
export const watchWindowsLauncher = ({
|
|
208
221
|
env = process.env,
|
|
209
222
|
platform = process.platform,
|
|
210
|
-
isAlive =
|
|
223
|
+
isAlive = launcherPidAlive,
|
|
211
224
|
onGone,
|
|
212
225
|
everyMs = 2000,
|
|
213
226
|
setIntervalFn = setInterval,
|
|
@@ -221,17 +234,31 @@ export const watchWindowsLauncher = ({
|
|
|
221
234
|
// error would end the daemon before it stops its seats. So the streams
|
|
222
235
|
// swallow errors from the moment the watch is armed, not only after the
|
|
223
236
|
// launcher's exit is noticed up to two seconds later.
|
|
224
|
-
|
|
237
|
+
//
|
|
238
|
+
// F637: a dead pipe is itself proof the launcher is gone (the pid check can
|
|
239
|
+
// be fooled by a reused pid), so EPIPE, or a write after the stream was
|
|
240
|
+
// destroyed, stops the daemon through the same onGone, once. Any other
|
|
241
|
+
// stream error is still swallowed.
|
|
242
|
+
let timer = null;
|
|
243
|
+
let gone = false;
|
|
244
|
+
const fire = () => {
|
|
245
|
+
if (gone) return;
|
|
246
|
+
gone = true;
|
|
247
|
+
if (timer !== null) clearIntervalFn(timer);
|
|
248
|
+
onGone(pid);
|
|
249
|
+
};
|
|
250
|
+
for (const stream of streams) {
|
|
251
|
+
stream?.on?.('error', (error) => { if (PIPE_GONE.has(error?.code)) fire(); });
|
|
252
|
+
}
|
|
225
253
|
// Already gone when armed (the daemon is armed before its first tick): say
|
|
226
254
|
// so now, rather than after a poll and a heartbeat logged into a dead pipe.
|
|
227
255
|
if (!isAlive(pid)) {
|
|
228
|
-
|
|
256
|
+
fire();
|
|
229
257
|
return () => {};
|
|
230
258
|
}
|
|
231
|
-
|
|
259
|
+
timer = setIntervalFn(() => {
|
|
232
260
|
if (isAlive(pid)) return;
|
|
233
|
-
|
|
234
|
-
onGone(pid);
|
|
261
|
+
fire();
|
|
235
262
|
}, everyMs);
|
|
236
263
|
if (typeof timer?.unref === 'function') timer.unref();
|
|
237
264
|
return () => clearIntervalFn(timer);
|
|
@@ -85,6 +85,12 @@ export const recordKeyFor = (row, loadToken) => {
|
|
|
85
85
|
return scoped;
|
|
86
86
|
};
|
|
87
87
|
|
|
88
|
+
// F637: how long a 429 holds both loops off, at the least.
|
|
89
|
+
export const RATE_LIMIT_MIN_WAIT_MS = 60_000;
|
|
90
|
+
// ...and at the most, whatever Retry-After says.
|
|
91
|
+
export const RATE_LIMIT_MAX_WAIT_MS = 10 * 60_000;
|
|
92
|
+
export const RATE_LIMIT_NOTICE = "the server is rate-limiting this computer's daemon key; more than one Commonly daemon may be running on it";
|
|
93
|
+
|
|
88
94
|
export const createDaemonSupervisor = ({
|
|
89
95
|
record,
|
|
90
96
|
client,
|
|
@@ -112,6 +118,15 @@ export const createDaemonSupervisor = ({
|
|
|
112
118
|
let reconnectAfter = 0;
|
|
113
119
|
const recentStarts = [];
|
|
114
120
|
|
|
121
|
+
// F637: true from a 429 until the next success, so the duplicate-daemon
|
|
122
|
+
// notice is logged once per stretch of rate limiting.
|
|
123
|
+
let rateLimited = false;
|
|
124
|
+
// F637 review: bumped by every failure that sets a wait. A request records
|
|
125
|
+
// it when it starts, and its success clears the wait only if no failure came
|
|
126
|
+
// after that start: a heartbeat in flight when a tick got a 429 must not
|
|
127
|
+
// cut the cooldown short by succeeding (or, below, by failing some other way).
|
|
128
|
+
let failureEpoch = 0;
|
|
129
|
+
|
|
115
130
|
const connectionFailure = (error, label) => {
|
|
116
131
|
if (isTerminalAuthError(error)) {
|
|
117
132
|
stopped = true;
|
|
@@ -119,13 +134,34 @@ export const createDaemonSupervisor = ({
|
|
|
119
134
|
return;
|
|
120
135
|
}
|
|
121
136
|
reconnectFailures += 1;
|
|
122
|
-
|
|
137
|
+
failureEpoch += 1;
|
|
138
|
+
if (error?.status === 429) {
|
|
139
|
+
// The server's limiter keys on this computer's daemon key. Retrying in
|
|
140
|
+
// a second or two keeps it shut, for every copy sharing the key, so wait
|
|
141
|
+
// at least a minute, or longer if the server asked for longer, but never
|
|
142
|
+
// past 10 minutes: a proxy or self-hosted limiter sending
|
|
143
|
+
// `Retry-After: 86400` must not silence the poll and heartbeat for a day.
|
|
144
|
+
const wait = Math.min(
|
|
145
|
+
Math.max(Number(error.retryAfterMs) || 0, RATE_LIMIT_MIN_WAIT_MS),
|
|
146
|
+
RATE_LIMIT_MAX_WAIT_MS,
|
|
147
|
+
);
|
|
148
|
+
reconnectAfter = Math.max(reconnectAfter, now() + wait);
|
|
149
|
+
if (!rateLimited) {
|
|
150
|
+
rateLimited = true;
|
|
151
|
+
log(RATE_LIMIT_NOTICE);
|
|
152
|
+
}
|
|
153
|
+
} else {
|
|
154
|
+
// Never shorter than a wait already set (a 429's cooldown).
|
|
155
|
+
reconnectAfter = Math.max(reconnectAfter, now() + reconnectDelayMs(reconnectFailures, random));
|
|
156
|
+
}
|
|
123
157
|
log(`${label}: ${error.message}; reconnect after ${Math.round((reconnectAfter - now()) / 1000)}s`);
|
|
124
158
|
};
|
|
125
159
|
|
|
126
|
-
const connectionRestored = () => {
|
|
160
|
+
const connectionRestored = (startedAtEpoch) => {
|
|
161
|
+
if (startedAtEpoch !== failureEpoch) return;
|
|
127
162
|
reconnectFailures = 0;
|
|
128
163
|
reconnectAfter = 0;
|
|
164
|
+
rateLimited = false;
|
|
129
165
|
};
|
|
130
166
|
|
|
131
167
|
const persist = () => {
|
|
@@ -503,6 +539,7 @@ export const createDaemonSupervisor = ({
|
|
|
503
539
|
|
|
504
540
|
const tick = async () => {
|
|
505
541
|
if (stopped || now() < reconnectAfter) return;
|
|
542
|
+
const startedAtEpoch = failureEpoch;
|
|
506
543
|
let assigned;
|
|
507
544
|
try {
|
|
508
545
|
assigned = await client.get('/api/agent-binding/assigned');
|
|
@@ -510,7 +547,7 @@ export const createDaemonSupervisor = ({
|
|
|
510
547
|
connectionFailure(error, 'work-list fetch failed');
|
|
511
548
|
return;
|
|
512
549
|
}
|
|
513
|
-
connectionRestored();
|
|
550
|
+
connectionRestored(startedAtEpoch);
|
|
514
551
|
const rows = Array.isArray(assigned?.agents) ? assigned.agents : [];
|
|
515
552
|
|
|
516
553
|
const bound = [];
|
|
@@ -601,13 +638,18 @@ export const createDaemonSupervisor = ({
|
|
|
601
638
|
|
|
602
639
|
const heartbeat = async () => {
|
|
603
640
|
if (stopped || now() < reconnectAfter) return;
|
|
641
|
+
const startedAtEpoch = failureEpoch;
|
|
604
642
|
try {
|
|
643
|
+
const inventory = await runtimeInventory();
|
|
644
|
+
// F637 review: a 429 (or a stop) can land while the inventory is read;
|
|
645
|
+
// the post must honour it, not go out on the check made before.
|
|
646
|
+
if (stopped || now() < reconnectAfter) return;
|
|
605
647
|
await client.post(`/api/machines/${record.machineDbId}/heartbeat`, {
|
|
606
648
|
...machineReport(),
|
|
607
649
|
agents: agentStates(),
|
|
608
|
-
runtimeInventory:
|
|
650
|
+
runtimeInventory: inventory,
|
|
609
651
|
});
|
|
610
|
-
connectionRestored();
|
|
652
|
+
connectionRestored(startedAtEpoch);
|
|
611
653
|
} catch (error) {
|
|
612
654
|
connectionFailure(error, 'heartbeat failed');
|
|
613
655
|
}
|
|
@@ -36,6 +36,12 @@ const LOGIN_FAILED_WORDINGS = [
|
|
|
36
36
|
// The wrapper's own refusals of a Claude login (adapters/claude.js).
|
|
37
37
|
/the Claude login on this machine expires in/,
|
|
38
38
|
/refusing a Claude login/,
|
|
39
|
+
// F661: a Linux seat with no token or key of its own to sign in with. These
|
|
40
|
+
// two are ^-anchored: they match the adapter's own refusal, thrown before
|
|
41
|
+
// anything spawns and so reaching here unprefixed (no "claude exited …:"),
|
|
42
|
+
// and never the same words echoed in a model's or tool's output.
|
|
43
|
+
/^workspace Claude agents on Linux need your own Claude token or an API key/,
|
|
44
|
+
/^public Claude agents on Linux need ANTHROPIC_API_KEY/,
|
|
39
45
|
];
|
|
40
46
|
// F436: what Claude Code prints, and exits 1 on, when it has no login on the
|
|
41
47
|
// computer (2.1.318, walked on windows-latest). No key is wrong and no allowance
|