sideby 0.16.1 → 0.18.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 (128) hide show
  1. package/README.md +7 -3
  2. package/ai-tasks.json +90 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +25 -1
  5. package/dist/src/cli/commands.js +802 -15
  6. package/dist/src/cli/json-schemas.js +252 -1
  7. package/dist/src/cli/main.js +143 -4
  8. package/dist/src/core/after-install.d.ts +54 -0
  9. package/dist/src/core/after-install.js +78 -0
  10. package/dist/src/core/ask.d.ts +222 -0
  11. package/dist/src/core/ask.js +465 -0
  12. package/dist/src/core/attachments.d.ts +50 -0
  13. package/dist/src/core/attachments.js +442 -0
  14. package/dist/src/core/autostart.d.ts +118 -0
  15. package/dist/src/core/autostart.js +302 -0
  16. package/dist/src/core/brand-mark.d.ts +49 -11
  17. package/dist/src/core/brand-mark.js +116 -38
  18. package/dist/src/core/config.d.ts +102 -0
  19. package/dist/src/core/config.js +289 -11
  20. package/dist/src/core/desktop-app.d.ts +1 -1
  21. package/dist/src/core/desktop-app.js +2 -2
  22. package/dist/src/core/edit-settings.d.ts +24 -0
  23. package/dist/src/core/edit-settings.js +97 -0
  24. package/dist/src/core/handoff-brief.d.ts +4 -2
  25. package/dist/src/core/handoff-brief.js +6 -1
  26. package/dist/src/core/handoff-chain.d.ts +24 -0
  27. package/dist/src/core/handoff-chain.js +2 -0
  28. package/dist/src/core/handoff-run.d.ts +4 -3
  29. package/dist/src/core/handoff-run.js +14 -9
  30. package/dist/src/core/launch.d.ts +17 -4
  31. package/dist/src/core/launch.js +32 -24
  32. package/dist/src/core/local-build.d.ts +17 -5
  33. package/dist/src/core/local-build.js +61 -23
  34. package/dist/src/core/lock.d.ts +30 -0
  35. package/dist/src/core/lock.js +143 -0
  36. package/dist/src/core/probe.d.ts +78 -0
  37. package/dist/src/core/probe.js +127 -0
  38. package/dist/src/core/quota-levels.d.ts +6 -1
  39. package/dist/src/core/quota-levels.js +16 -5
  40. package/dist/src/core/same-login.d.ts +9 -4
  41. package/dist/src/core/same-login.js +9 -4
  42. package/dist/src/core/secret-file.d.ts +26 -0
  43. package/dist/src/core/secret-file.js +126 -7
  44. package/dist/src/core/task-spec.d.ts +95 -0
  45. package/dist/src/core/task-spec.js +209 -0
  46. package/dist/src/core/terminal.d.ts +93 -0
  47. package/dist/src/core/terminal.js +376 -0
  48. package/dist/src/core/update.d.ts +34 -12
  49. package/dist/src/core/update.js +96 -84
  50. package/dist/src/desktop/icon.js +12 -15
  51. package/dist/src/families/claude/ai-task.d.ts +8 -0
  52. package/dist/src/families/claude/ai-task.js +38 -0
  53. package/dist/src/families/claude/handoff-hook.js +4 -4
  54. package/dist/src/families/claude/index.js +6 -0
  55. package/dist/src/families/claude/quota-cache.d.ts +24 -7
  56. package/dist/src/families/claude/quota-cache.js +72 -21
  57. package/dist/src/families/codex/handoff-hook.js +4 -4
  58. package/dist/src/families/codex/index.js +16 -0
  59. package/dist/src/families/codex/login-key.d.ts +8 -0
  60. package/dist/src/families/codex/login-key.js +33 -0
  61. package/dist/src/families/grok/handoff-hook.js +4 -4
  62. package/dist/src/families/grok/index.js +4 -0
  63. package/dist/src/families/login-keys.d.ts +6 -0
  64. package/dist/src/families/login-keys.js +6 -0
  65. package/dist/src/families/pi/index.js +5 -0
  66. package/dist/src/handoff/hook.js +51 -30
  67. package/dist/src/handoff/levels.d.ts +24 -0
  68. package/dist/src/handoff/levels.js +70 -0
  69. package/dist/src/handoff/messages.d.ts +6 -3
  70. package/dist/src/handoff/messages.js +20 -7
  71. package/dist/src/handoff/reader.d.ts +6 -3
  72. package/dist/src/menubar/agent.d.ts +3 -0
  73. package/dist/src/menubar/agent.js +21 -0
  74. package/dist/src/menubar/script.d.ts +8 -0
  75. package/dist/src/menubar/script.js +457 -0
  76. package/dist/src/menubar/snapshot.d.ts +115 -0
  77. package/dist/src/menubar/snapshot.js +255 -0
  78. package/dist/src/menubar/strings.d.ts +87 -0
  79. package/dist/src/menubar/strings.js +88 -0
  80. package/dist/src/panel/background.js +15 -21
  81. package/dist/src/panel/handler.d.ts +41 -2
  82. package/dist/src/panel/handler.js +394 -10
  83. package/dist/src/panel/i18n.d.ts +205 -2
  84. package/dist/src/panel/i18n.js +441 -35
  85. package/dist/src/panel/page-logic.d.ts +301 -0
  86. package/dist/src/panel/page-logic.js +532 -0
  87. package/dist/src/panel/page-script.js +1135 -185
  88. package/dist/src/panel/page-styles.js +111 -32
  89. package/dist/src/panel/page.d.ts +12 -0
  90. package/dist/src/panel/page.js +7 -0
  91. package/dist/src/panel/server.d.ts +16 -2
  92. package/dist/src/panel/server.js +41 -13
  93. package/dist/src/plugins/check.d.ts +47 -0
  94. package/dist/src/plugins/check.js +544 -0
  95. package/dist/src/plugins/scaffold.d.ts +21 -0
  96. package/dist/src/plugins/scaffold.js +123 -0
  97. package/dist/src/quota/statusline-tap.js +1 -1
  98. package/dist/src/runtime.d.ts +19 -1
  99. package/dist/src/runtime.js +53 -14
  100. package/dist/src/types.d.ts +33 -0
  101. package/package.json +4 -3
  102. package/schemas/ask-choices.json +168 -0
  103. package/schemas/ask-print.json +87 -0
  104. package/schemas/ask.json +180 -0
  105. package/schemas/autostart.json +165 -0
  106. package/schemas/config-get.json +132 -0
  107. package/schemas/config-set.json +107 -0
  108. package/schemas/config.json +90 -7
  109. package/schemas/edit.json +119 -0
  110. package/schemas/error.json +4 -0
  111. package/schemas/families.json +4 -0
  112. package/schemas/key.json +93 -0
  113. package/schemas/list.json +4 -0
  114. package/schemas/local.json +1 -1
  115. package/schemas/menubar-snapshot.json +646 -0
  116. package/schemas/menubar-start.json +112 -0
  117. package/schemas/menubar.json +165 -0
  118. package/schemas/plugins-check.json +113 -0
  119. package/schemas/plugins-new.json +87 -0
  120. package/schemas/terminal.json +152 -0
  121. package/schemas/try.json +109 -0
  122. package/schemas/update.json +4 -0
  123. package/skills/sideby/SKILL.md +16 -6
  124. package/skills/sideby/references/accounts.md +1 -1
  125. package/skills/sideby/references/ai-tasks.md +126 -0
  126. package/skills/sideby/references/handoff.md +3 -1
  127. package/skills/sideby/references/panel.md +20 -0
  128. package/skills/sideby/references/update.md +1 -1
@@ -0,0 +1,143 @@
1
+ // Lock files: who holds one, how the holder shows it is still alive, and when a lock counts as left behind.
2
+ // A lock is a file created exclusively (mode 600) holding `<pid> <ms since epoch>`. Its holder touches it every
3
+ // `beatMs`; a lock nobody touched for `staleMs` is free even while its pid runs, because a Portal that ends the worker
4
+ // thread holding it leaves a process (the same pid) that lives on. A dead pid frees it at once.
5
+ import { readFileSync } from 'node:fs';
6
+ import { open, readFile, rm, stat } from 'node:fs/promises';
7
+ /** Whether a Linux `/proc/<pid>/stat` line is of a zombie: the state after the parenthesised command name is `Z`. */
8
+ export function isZombieStat(line) {
9
+ return /\)\s+Z\s/.test(line.slice(line.lastIndexOf(')')));
10
+ }
11
+ /** Whether `pid` runs. A zombie (exited, nobody waited for it) answers signal 0 on Linux but holds nothing. */
12
+ export function processAlive(pid) {
13
+ try {
14
+ process.kill(pid, 0);
15
+ }
16
+ catch (err) {
17
+ return err.code === 'EPERM';
18
+ }
19
+ try {
20
+ return !isZombieStat(readFileSync(`/proc/${pid}/stat`, 'utf8'));
21
+ }
22
+ catch {
23
+ return true; // no /proc (macOS): signal 0 is the answer
24
+ }
25
+ }
26
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
27
+ /**
28
+ * Takes the lock `file` (its directory must exist). Returns its release function, or null when another holder keeps
29
+ * it (after waiting, with `wait`). Errors other than the file existing are thrown.
30
+ */
31
+ export async function takeFileLock(file, opts) {
32
+ const now = opts.now ?? Date.now;
33
+ const deadline = opts.wait ? now() + opts.wait.timeoutMs : 0;
34
+ for (;;) {
35
+ const release = await tryTake(file, opts, now);
36
+ if (release || !opts.wait || now() >= deadline)
37
+ return release;
38
+ await sleep(opts.wait.pollMs);
39
+ }
40
+ }
41
+ async function tryTake(file, opts, now) {
42
+ const alive = opts.alive ?? processAlive;
43
+ const grace = opts.writeGraceMs ?? opts.staleMs;
44
+ for (let attempt = 0; attempt < 2; attempt++) {
45
+ const me = `${process.pid} ${now()}`;
46
+ try {
47
+ const fh = await open(file, 'wx', 0o600);
48
+ try {
49
+ await fh.writeFile(me);
50
+ }
51
+ catch (err) {
52
+ await fh.close().catch(() => { });
53
+ throw err;
54
+ }
55
+ return hold(file, fh, me, opts.beatMs);
56
+ }
57
+ catch (err) {
58
+ if (err.code !== 'EEXIST')
59
+ throw err;
60
+ }
61
+ // Judging and removing a lock left behind happen under the guard: two takers that both judged it stale would
62
+ // otherwise let the slower one remove the lock the faster one has just made.
63
+ const freed = await guarded(file, async () => {
64
+ const text = await readFile(file, 'utf8').catch(() => null);
65
+ if (text === null)
66
+ return true;
67
+ const m = /^(\d+) (\d+)$/.exec(text);
68
+ // The file's time is the real clock's; `now` may be swapped, so the lock's age in touches uses the real one.
69
+ const sinceTouch = Date.now() - ((await stat(file).catch(() => null))?.mtimeMs ?? 0);
70
+ const held = m
71
+ ? alive(Number(m[1])) &&
72
+ (opts.maxMs === undefined || now() - Number(m[2]) < opts.maxMs) &&
73
+ sinceTouch < opts.staleMs
74
+ : sinceTouch < grace;
75
+ if (held)
76
+ return false;
77
+ await rm(file, { force: true });
78
+ return true;
79
+ });
80
+ if (!freed)
81
+ return null;
82
+ }
83
+ return null;
84
+ }
85
+ /** A guard older than this was left by a holder that stopped; nothing holds the guard for more than a few file calls. */
86
+ const GUARD_STALE_MS = 5000;
87
+ /**
88
+ * Runs `fn` while holding `<file>.guard`, a lock only for the read, the judgement and the removal of `file`. Waits up
89
+ * to a second for it; false (nothing run) when it stays busy.
90
+ */
91
+ async function guarded(file, fn) {
92
+ const guard = `${file}.guard`;
93
+ for (let i = 0; i < 200; i++) {
94
+ try {
95
+ const fh = await open(guard, 'wx', 0o600);
96
+ await fh.close();
97
+ }
98
+ catch (err) {
99
+ if (err.code !== 'EEXIST')
100
+ throw err;
101
+ const age = Date.now() - ((await stat(guard).catch(() => null))?.mtimeMs ?? Date.now());
102
+ if (age > GUARD_STALE_MS)
103
+ await rm(guard, { force: true });
104
+ else
105
+ await sleep(5);
106
+ continue;
107
+ }
108
+ try {
109
+ return await fn();
110
+ }
111
+ finally {
112
+ await rm(guard, { force: true });
113
+ }
114
+ }
115
+ return false;
116
+ }
117
+ /**
118
+ * Holds the lock through its open handle: the heartbeat touches that file, so a holder whose lock was taken over (and
119
+ * removed) touches only its own removed file, never the lock that replaced it.
120
+ */
121
+ function hold(file, fh, me, beatMs) {
122
+ const beat = setInterval(() => {
123
+ const at = new Date();
124
+ fh.utimes(at, at).catch(() => { });
125
+ }, beatMs);
126
+ beat.unref();
127
+ let released = false;
128
+ return async () => {
129
+ if (released)
130
+ return;
131
+ released = true;
132
+ clearInterval(beat);
133
+ await fh.close().catch(() => { });
134
+ const remove = async () => {
135
+ if ((await readFile(file, 'utf8').catch(() => '')) === me)
136
+ await rm(file, { force: true });
137
+ return true;
138
+ };
139
+ // Under the guard, so a taker cannot replace the lock between the read and the removal. Without it (busy for a
140
+ // second) the lock stays: its heartbeat has stopped, so it is free once `staleMs` has passed.
141
+ await guarded(file, remove).catch(() => false);
142
+ };
143
+ }
@@ -0,0 +1,78 @@
1
+ import { HookBus } from '../plugins/bus.ts';
2
+ import type { Account, Env, FamilyDef } from '../types.ts';
3
+ import { type PreparedLaunch } from './launch.ts';
4
+ /** How long `sideby try` waits for the Host (spec §3.28). The spawner enforces it. */
5
+ export declare const PROBE_TIMEOUT_MS = 60000;
6
+ /** Combined stdout and stderr kept after redaction, in bytes. */
7
+ export declare const PROBE_OUTPUT_MAX_BYTES = 2048;
8
+ /**
9
+ * What the injected spawner receives. It must start `bin` with `args` only, in `cwd`, with `env`,
10
+ * and with stdin ignored (not a terminal and not a pipe the Host can wait on). When `timeoutMs`
11
+ * elapses it stops the process and resolves with `timedOut: true`. Errors must not include `env`
12
+ * or anything read from a Secret File.
13
+ */
14
+ export interface ProbeSpawnRequest {
15
+ bin: string;
16
+ args: readonly string[];
17
+ env: Env;
18
+ cwd: string;
19
+ timeoutMs: number;
20
+ /** Always `ignore`: the probe is not interactive. */
21
+ stdin: 'ignore';
22
+ }
23
+ export interface ProbeSpawnResult {
24
+ /** Process exit code, or null when it timed out or the code could not be read. */
25
+ exitCode: number | null;
26
+ stdout: string;
27
+ stderr: string;
28
+ /** True when the spawner stopped the process because `timeoutMs` elapsed. */
29
+ timedOut: boolean;
30
+ }
31
+ export interface ProbeDeps {
32
+ family: FamilyDef;
33
+ /** The environment sideby itself is running in: the same `baseEnv` Launch copies. */
34
+ baseEnv: Env;
35
+ /** Working directory for the Host. The caller creates this temp directory. */
36
+ cwd: string;
37
+ spawn: (req: ProbeSpawnRequest) => Promise<ProbeSpawnResult>;
38
+ /** Account arguments from config, passed through Launch the same way `sideby run` does. */
39
+ accountArgs?: readonly string[];
40
+ /** What Launch would set as `SIDEBY_LABEL`. Defaults to the account ref. */
41
+ label?: string;
42
+ /** `launch.before` hooks. Pass the runtime bus so the probe sees the same environment as Launch. */
43
+ bus?: HookBus;
44
+ /**
45
+ * The Launch already prepared with `probe.args` as the user's arguments (the runtime's `prepareLaunch`), so its
46
+ * hooks and config arguments are applied once; `accountArgs`, `label` and `bus` are then unused.
47
+ */
48
+ launch?: PreparedLaunch;
49
+ /** Defaults to {@link PROBE_TIMEOUT_MS}. */
50
+ timeoutMs?: number;
51
+ }
52
+ export interface ProbeResult {
53
+ /** True when the Host exited 0 before the timeout. */
54
+ ok: boolean;
55
+ exitCode: number | null;
56
+ /**
57
+ * The first 2 KiB of stdout followed by stderr. Secret File values of length 4 or more are
58
+ * replaced with `***` before this cut, so a value that straddles the cut cannot leak.
59
+ */
60
+ output: string;
61
+ /** True when the spawner stopped the Host at the timeout. `ok` is then false. */
62
+ timedOut: boolean;
63
+ }
64
+ /**
65
+ * Runs the Family's probe the way Launch would start the Host: `prepareLaunch`'s environment and
66
+ * arguments (with `probe.args` as the user's arguments), the caller's temp directory as cwd, stdin ignored, and a 60s
67
+ * timeout the spawner enforces. Returns the exit code and the redacted output.
68
+ * Throws a UserError when the Family has no probe; the message says this tool cannot be tried
69
+ * and to start the account with `sideby run` instead.
70
+ */
71
+ export declare function runProbe(account: Account, deps: ProbeDeps): Promise<ProbeResult>;
72
+ /**
73
+ * The real spawner for {@link ProbeDeps.spawn}. The Host leads its own process group, so the timeout stops it and
74
+ * any child it started; the result comes at once, even while a child still holds the output pipes open.
75
+ */
76
+ export declare function spawnProbe(request: ProbeSpawnRequest): Promise<ProbeSpawnResult>;
77
+ /** Replaces each secret of length 4 or more. Longer values go first so one cannot hide inside another. */
78
+ export declare function redactSecrets(text: string, values: readonly string[]): string;
@@ -0,0 +1,127 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { HookBus } from '../plugins/bus.js';
3
+ import { UserError } from './errors.js';
4
+ import { prepareLaunch } from './launch.js';
5
+ import { readSecretFile } from './secret-file.js';
6
+ /** How long `sideby try` waits for the Host (spec §3.28). The spawner enforces it. */
7
+ export const PROBE_TIMEOUT_MS = 60_000;
8
+ /** Combined stdout and stderr kept after redaction, in bytes. */
9
+ export const PROBE_OUTPUT_MAX_BYTES = 2048;
10
+ /**
11
+ * Runs the Family's probe the way Launch would start the Host: `prepareLaunch`'s environment and
12
+ * arguments (with `probe.args` as the user's arguments), the caller's temp directory as cwd, stdin ignored, and a 60s
13
+ * timeout the spawner enforces. Returns the exit code and the redacted output.
14
+ * Throws a UserError when the Family has no probe; the message says this tool cannot be tried
15
+ * and to start the account with `sideby run` instead.
16
+ */
17
+ export async function runProbe(account, deps) {
18
+ const probe = deps.family.probe;
19
+ if (!probe)
20
+ throw new UserError(`This tool cannot be tried. Start ${account.ref} with \`sideby run ${account.ref}\` and send one short message instead.`, { code: 'no-probe' });
21
+ const prepared = deps.launch ??
22
+ (await prepareLaunch({
23
+ account,
24
+ family: deps.family,
25
+ baseEnv: deps.baseEnv,
26
+ accountArgs: deps.accountArgs ?? [],
27
+ userArgs: probe.args,
28
+ command: 'run',
29
+ bus: deps.bus ?? new HookBus(),
30
+ ...(deps.label ? { label: deps.label } : {}),
31
+ }));
32
+ const secrets = account.secretFile
33
+ ? Object.values(await readSecretFile(account.secretFile, deps.baseEnv))
34
+ : [];
35
+ const spawned = await deps.spawn({
36
+ bin: prepared.bin,
37
+ // Family defaults, config arguments and `launch.before` changes, as `sideby run` passes them.
38
+ args: prepared.args,
39
+ env: prepared.env,
40
+ cwd: deps.cwd,
41
+ timeoutMs: deps.timeoutMs ?? PROBE_TIMEOUT_MS,
42
+ stdin: 'ignore',
43
+ });
44
+ const output = clip(redactSecrets(spawned.stdout + spawned.stderr, secrets), PROBE_OUTPUT_MAX_BYTES);
45
+ return {
46
+ ok: spawned.exitCode === 0 && !spawned.timedOut,
47
+ exitCode: spawned.exitCode,
48
+ output,
49
+ timedOut: spawned.timedOut,
50
+ };
51
+ }
52
+ /** Output kept per stream before redaction, in characters. */
53
+ const SPAWN_KEEP = 65536;
54
+ /**
55
+ * The real spawner for {@link ProbeDeps.spawn}. The Host leads its own process group, so the timeout stops it and
56
+ * any child it started; the result comes at once, even while a child still holds the output pipes open.
57
+ */
58
+ export function spawnProbe(request) {
59
+ return new Promise((resolve) => {
60
+ const child = spawn(request.bin, [...request.args], {
61
+ cwd: request.cwd,
62
+ env: request.env,
63
+ stdio: [request.stdin, 'pipe', 'pipe'],
64
+ detached: true,
65
+ });
66
+ let stdout = '', stderr = '', timedOut = false, done = false;
67
+ const finish = (result) => {
68
+ if (done)
69
+ return;
70
+ done = true;
71
+ clearTimeout(timer);
72
+ resolve(result);
73
+ };
74
+ const timer = setTimeout(() => {
75
+ timedOut = true;
76
+ try {
77
+ if (child.pid)
78
+ process.kill(-child.pid, 'SIGKILL');
79
+ }
80
+ catch {
81
+ child.kill('SIGKILL');
82
+ }
83
+ child.stdout.destroy();
84
+ child.stderr.destroy();
85
+ // It may have exited already while a child of its own kept the pipes open.
86
+ if (child.exitCode !== null || child.signalCode !== null)
87
+ finish({ exitCode: null, stdout, stderr, timedOut });
88
+ }, request.timeoutMs);
89
+ child.stdout.on('data', (d) => {
90
+ if (stdout.length < SPAWN_KEEP)
91
+ stdout += d.toString();
92
+ });
93
+ child.stderr.on('data', (d) => {
94
+ if (stderr.length < SPAWN_KEEP)
95
+ stderr += d.toString();
96
+ });
97
+ child.on('error', () => finish({
98
+ exitCode: 1,
99
+ stdout: '',
100
+ stderr: 'Could not start the Host; check its installation and run `sideby try` again.',
101
+ timedOut: false,
102
+ }));
103
+ child.on('exit', () => {
104
+ if (timedOut)
105
+ finish({ exitCode: null, stdout, stderr, timedOut });
106
+ });
107
+ child.on('close', (exitCode) => finish({ exitCode, stdout, stderr, timedOut }));
108
+ });
109
+ }
110
+ /** Replaces each secret of length 4 or more. Longer values go first so one cannot hide inside another. */
111
+ export function redactSecrets(text, values) {
112
+ const needles = [...new Set(values.filter((v) => v.length >= 4))].sort((a, b) => b.length - a.length);
113
+ let out = text;
114
+ for (const needle of needles)
115
+ out = out.split(needle).join('***');
116
+ return out;
117
+ }
118
+ /** The first `max` bytes, never cutting a UTF-8 code point in half. */
119
+ function clip(text, max) {
120
+ const buf = Buffer.from(text, 'utf8');
121
+ if (buf.length <= max)
122
+ return text;
123
+ let n = max;
124
+ while (n > 0 && (buf[n] & 0xc0) === 0x80)
125
+ n--;
126
+ return buf.subarray(0, n).toString('utf8');
127
+ }
@@ -1,4 +1,4 @@
1
- import type { QuotaResult } from '../types.ts';
1
+ import type { QuotaResult, QuotaWindow } from '../types.ts';
2
2
  /**
3
3
  * How full a Quota window must be before the CLI and the Panel warn about it, and the Usage window both
4
4
  * report. One rule for both surfaces: the Panel interpolates these numbers into its inline script.
@@ -18,3 +18,8 @@ export declare function windowReset(resetsAt: string, now: Date): boolean;
18
18
  * must be self-contained; a test keeps the two equal.
19
19
  */
20
20
  export declare function quotaPressure(quota: QuotaResult | undefined, now: Date): number | null;
21
+ /**
22
+ * The windows that count toward Quota Pressure and have not reset, with `usedPercent` clamped to 0–100; null when
23
+ * the Account has no Quota or no window that counts (spec §3.26).
24
+ */
25
+ export declare function openWindows(quota: QuotaResult | undefined, now: Date): QuotaWindow[] | null;
@@ -25,14 +25,25 @@ export function windowReset(resetsAt, now) {
25
25
  * must be self-contained; a test keeps the two equal.
26
26
  */
27
27
  export function quotaPressure(quota, now) {
28
+ const windows = openWindows(quota, now);
29
+ if (windows === null)
30
+ return null;
31
+ let max = 0;
32
+ for (const w of windows)
33
+ max = Math.max(max, w.usedPercent);
34
+ return max;
35
+ }
36
+ /**
37
+ * The windows that count toward Quota Pressure and have not reset, with `usedPercent` clamped to 0–100; null when
38
+ * the Account has no Quota or no window that counts (spec §3.26).
39
+ */
40
+ export function openWindows(quota, now) {
28
41
  if (quota?.status !== 'ok')
29
42
  return null;
30
43
  const windows = quota.windows.filter((w) => !w.name);
31
44
  if (windows.length === 0)
32
45
  return null;
33
- let max = 0;
34
- for (const w of windows)
35
- if (!windowReset(w.resetsAt, now))
36
- max = Math.max(max, Math.min(100, Number(w.usedPercent) || 0));
37
- return max;
46
+ return windows
47
+ .filter((w) => !windowReset(w.resetsAt, now))
48
+ .map((w) => ({ ...w, usedPercent: Math.min(100, Number(w.usedPercent) || 0) }));
38
49
  }
@@ -1,18 +1,23 @@
1
1
  import type { Account, AccountIdentity, QuotaResult } from '../types.ts';
2
+ /** Families whose Accounts can be a Same Login (ADR-0016, ADR-0028). */
3
+ export declare const SAME_LOGIN_FAMILIES: ReadonlySet<string>;
2
4
  /**
3
- * Families whose Identity tells one Quota apart. Codex is left out: its Identity is an email only, and one email can
4
- * belong to several ChatGPT workspaces, each with its own Quota (ADR-0016).
5
+ * Families whose Identity alone does not tell one Quota apart, so two Accounts also need equal Login Keys. Codex: one
6
+ * email can belong to several ChatGPT workspaces, each with its own Quota (ADR-0028).
5
7
  */
6
- export declare const SAME_LOGIN_FAMILIES: ReadonlySet<string>;
8
+ export declare const LOGIN_KEY_FAMILIES: ReadonlySet<string>;
7
9
  export interface LoginMember {
8
10
  ref: string;
9
11
  family: string;
10
12
  kind: Account['kind'];
11
13
  identity?: AccountIdentity;
14
+ /** The opaque Login Key (ADR-0028), only for comparing here; never put into an output. */
15
+ loginKey?: string;
12
16
  }
13
17
  /**
14
18
  * Whether two Accounts are the same login: same Family (one that groups), both subscriptions, the same email, and the
15
- * same organization (both have one and it is equal, or neither has one). Without an email nothing groups.
19
+ * same organization (both have one and it is equal, or neither has one). Without an email nothing groups. In a Family
20
+ * of `LOGIN_KEY_FAMILIES` both must also have a Login Key, and the keys must be equal.
16
21
  */
17
22
  export declare function isSameLogin(a: LoginMember, b: LoginMember): boolean;
18
23
  /** Ref → the other refs of its Same Login, in the order given; Accounts without one are left out. */
@@ -1,12 +1,15 @@
1
+ /** Families whose Accounts can be a Same Login (ADR-0016, ADR-0028). */
2
+ export const SAME_LOGIN_FAMILIES = new Set(['claude', 'codex']);
1
3
  /**
2
- * Families whose Identity tells one Quota apart. Codex is left out: its Identity is an email only, and one email can
3
- * belong to several ChatGPT workspaces, each with its own Quota (ADR-0016).
4
+ * Families whose Identity alone does not tell one Quota apart, so two Accounts also need equal Login Keys. Codex: one
5
+ * email can belong to several ChatGPT workspaces, each with its own Quota (ADR-0028).
4
6
  */
5
- export const SAME_LOGIN_FAMILIES = new Set(['claude']);
7
+ export const LOGIN_KEY_FAMILIES = new Set(['codex']);
6
8
  const norm = (s) => s?.trim().toLowerCase();
7
9
  /**
8
10
  * Whether two Accounts are the same login: same Family (one that groups), both subscriptions, the same email, and the
9
- * same organization (both have one and it is equal, or neither has one). Without an email nothing groups.
11
+ * same organization (both have one and it is equal, or neither has one). Without an email nothing groups. In a Family
12
+ * of `LOGIN_KEY_FAMILIES` both must also have a Login Key, and the keys must be equal.
10
13
  */
11
14
  export function isSameLogin(a, b) {
12
15
  if (a.ref === b.ref || a.family !== b.family || !SAME_LOGIN_FAMILIES.has(a.family))
@@ -16,6 +19,8 @@ export function isSameLogin(a, b) {
16
19
  const ea = norm(a.identity?.email);
17
20
  if (!ea || ea !== norm(b.identity?.email))
18
21
  return false;
22
+ if (LOGIN_KEY_FAMILIES.has(a.family) && (!a.loginKey || a.loginKey !== b.loginKey))
23
+ return false;
19
24
  return norm(a.identity?.org) === norm(b.identity?.org);
20
25
  }
21
26
  /** Ref → the other refs of its Same Login, in the order given; Accounts without one are left out. */
@@ -1,3 +1,4 @@
1
+ import type { FamilyDef } from '../types.ts';
1
2
  import { UserError } from './errors.ts';
2
3
  export declare class SecretFileError extends UserError {
3
4
  }
@@ -28,3 +29,28 @@ export declare function inspectSecretFile(file: string): Promise<SecretFileState
28
29
  /** Reads a Secret File after inspectSecretFile accepts it. */
29
30
  export declare function readSecretFile(file: string, env?: Readonly<Record<string, string | undefined>>): Promise<Record<string, string>>;
30
31
  export declare function secretFileTemplate(vars: readonly string[], familyTitle: string): string;
32
+ /** Variable names `sideby key` accepts, such as `ANTHROPIC_AUTH_TOKEN`. */
33
+ export declare const SECRET_VAR_NAME: RegExp;
34
+ export interface SetSecretResult {
35
+ /** Path whose bytes were written. When `file` is a symlink, this is its real target. */
36
+ path: string;
37
+ /** True when `file` was a symlink. The link itself is unchanged. */
38
+ viaLink: boolean;
39
+ name: string;
40
+ /** `replaced` keeps the assignment's line; `appended` adds one at the end. */
41
+ action: 'replaced' | 'appended';
42
+ }
43
+ /**
44
+ * The Secret File variable `sideby key` writes when the user does not pass `--var`.
45
+ * Uses `family.secretVar` when the Family sets one, otherwise the first `apiVars` entry
46
+ * that ends in `_KEY` or `_TOKEN`. Throws when the Family has neither, and says to pass `--var`.
47
+ */
48
+ export declare function secretVarFor(family: Pick<FamilyDef, 'title' | 'apiVars' | 'secretVar'>): string;
49
+ /**
50
+ * Writes one assignment into a Secret File. The line that assigns `name` is replaced and stays
51
+ * where it was; every other line is kept byte for byte. When `name` is absent, a line is appended.
52
+ * The write is atomic and the file ends at mode 600. A symlink is left in place and the bytes go
53
+ * to its real target, which `path` reports. `name` must match {@link SECRET_VAR_NAME}. A value
54
+ * that contains a newline is rejected. The value is never included in an error or in the result.
55
+ */
56
+ export declare function setSecret(file: string, name: string, value: string): Promise<SetSecretResult>;
@@ -1,5 +1,6 @@
1
- import { lstat, readFile } from 'node:fs/promises';
1
+ import { readFile } from 'node:fs/promises';
2
2
  import { UserError } from './errors.js';
3
+ import { lstatOrNull, realpathOrNull, writeFileAtomic } from './fs-safe.js';
3
4
  export class SecretFileError extends UserError {
4
5
  }
5
6
  const LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/;
@@ -82,13 +83,9 @@ export function parseSecretFile(text, file, env = {}) {
82
83
  * with mode 600. Only the file's type and mode are inspected, never its contents.
83
84
  */
84
85
  export async function inspectSecretFile(file) {
85
- let st;
86
- try {
87
- st = await lstat(file);
88
- }
89
- catch {
86
+ const st = await lstatOrNull(file);
87
+ if (!st)
90
88
  return { kind: 'missing' };
91
- }
92
89
  if (!st.isFile())
93
90
  return { kind: 'not-file' };
94
91
  const mode = st.mode & 0o777;
@@ -114,3 +111,125 @@ export function secretFileTemplate(vars, familyTitle) {
114
111
  ];
115
112
  return lines.join('\n');
116
113
  }
114
+ /** Variable names `sideby key` accepts, such as `ANTHROPIC_AUTH_TOKEN`. */
115
+ export const SECRET_VAR_NAME = /^[A-Z][A-Z0-9_]*$/;
116
+ const KEY_VAR = /(?:_KEY|_TOKEN)$/;
117
+ const ASSIGN = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
118
+ /**
119
+ * The Secret File variable `sideby key` writes when the user does not pass `--var`.
120
+ * Uses `family.secretVar` when the Family sets one, otherwise the first `apiVars` entry
121
+ * that ends in `_KEY` or `_TOKEN`. Throws when the Family has neither, and says to pass `--var`.
122
+ */
123
+ export function secretVarFor(family) {
124
+ const name = family.secretVar ?? family.apiVars.find((v) => SECRET_VAR_NAME.test(v) && KEY_VAR.test(v));
125
+ if (!name || !SECRET_VAR_NAME.test(name))
126
+ throw new SecretFileError(`${family.title} has no default key variable. Run \`sideby key <account> --var <NAME>\` with the variable that tool's documentation names.`);
127
+ return name;
128
+ }
129
+ /**
130
+ * Writes one assignment into a Secret File. The line that assigns `name` is replaced and stays
131
+ * where it was; every other line is kept byte for byte. When `name` is absent, a line is appended.
132
+ * The write is atomic and the file ends at mode 600. A symlink is left in place and the bytes go
133
+ * to its real target, which `path` reports. `name` must match {@link SECRET_VAR_NAME}. A value
134
+ * that contains a newline is rejected. The value is never included in an error or in the result.
135
+ */
136
+ export async function setSecret(file, name, value) {
137
+ if (!SECRET_VAR_NAME.test(name))
138
+ throw new SecretFileError(`variable name must match [A-Z][A-Z0-9_]* (for example ANTHROPIC_AUTH_TOKEN). Run \`sideby key <account> --var <NAME>\`.`);
139
+ if (value.includes('\n') || value.includes('\r'))
140
+ throw new SecretFileError(`${name} must be a single line. Run \`sideby key <account>\` and enter one line, or fill the key in the Panel.`);
141
+ const formatted = `${name}=${formatSecretValue(value)}`;
142
+ const located = await locateSecretFile(file);
143
+ let previous = '';
144
+ if (located.existed) {
145
+ try {
146
+ previous = await readFile(located.path, 'utf8');
147
+ }
148
+ catch (err) {
149
+ throw writeFailed(located.path, err);
150
+ }
151
+ }
152
+ const next = assignLine(previous, name, formatted);
153
+ try {
154
+ await writeFileAtomic(located.path, next.text, 0o600);
155
+ }
156
+ catch (err) {
157
+ throw writeFailed(located.path, err);
158
+ }
159
+ return { path: located.path, viaLink: located.viaLink, name, action: next.action };
160
+ }
161
+ /** Where the bytes go. A symlink is not followed by the writer; the caller passes the real target. */
162
+ async function locateSecretFile(file) {
163
+ const st = await lstatOrNull(file);
164
+ if (!st)
165
+ return { path: file, viaLink: false, existed: false };
166
+ if (st.isSymbolicLink()) {
167
+ const real = await realpathOrNull(file);
168
+ if (!real)
169
+ throw new SecretFileError(`${file} is a broken link. Point it at a proxy.env file, or replace the link with a file, then run \`sideby key\` again.`);
170
+ const target = await lstatOrNull(real);
171
+ if (!target?.isFile())
172
+ throw new SecretFileError(`${file} points at ${real}, which is not a file. Point the link at a proxy.env file, then run \`sideby key\` again.`);
173
+ return { path: real, viaLink: true, existed: true };
174
+ }
175
+ if (st.isDirectory())
176
+ throw new SecretFileError(`${file} is a directory. \`sideby key\` writes the proxy.env file; move that directory aside, then run \`sideby key\` again.`);
177
+ if (!st.isFile())
178
+ throw new SecretFileError(`${file} is not a regular file. Replace it with a proxy.env file, then run \`sideby key\` again.`);
179
+ return { path: file, viaLink: false, existed: true };
180
+ }
181
+ function assignLine(text, name, formatted) {
182
+ const lines = splitKeepEnds(text);
183
+ let replaced = false;
184
+ const rebuilt = lines
185
+ .map((line) => {
186
+ if (assignmentName(line.body) !== name)
187
+ return line.body + line.eol;
188
+ replaced = true;
189
+ return formatted + line.eol;
190
+ })
191
+ .join('');
192
+ if (replaced)
193
+ return { text: rebuilt, action: 'replaced' };
194
+ const sep = text.length > 0 && !text.endsWith('\n') ? '\n' : '';
195
+ return { text: `${text}${sep}${formatted}\n`, action: 'appended' };
196
+ }
197
+ function assignmentName(body) {
198
+ const trimmed = body.trim();
199
+ if (!trimmed || trimmed.startsWith('#'))
200
+ return null;
201
+ return ASSIGN.exec(body)?.[1] ?? null;
202
+ }
203
+ /** A value `parseSecretFile` reads back unchanged. Single quotes stay literal; nothing is executed. */
204
+ function formatSecretValue(value) {
205
+ if (/^[A-Za-z0-9_./:@%+-]*$/.test(value))
206
+ return value;
207
+ if (!value.includes("'"))
208
+ return `'${value}'`;
209
+ const escaped = value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\$/g, '\\$');
210
+ return `"${escaped}"`;
211
+ }
212
+ function splitKeepEnds(text) {
213
+ if (text === '')
214
+ return [];
215
+ const out = [];
216
+ const re = /\r\n|\n/g;
217
+ let last = 0;
218
+ for (let m = re.exec(text); m; m = re.exec(text)) {
219
+ out.push({ body: text.slice(last, m.index), eol: m[0] });
220
+ last = m.index + m[0].length;
221
+ }
222
+ if (last < text.length)
223
+ out.push({ body: text.slice(last), eol: '' });
224
+ return out;
225
+ }
226
+ function writeFailed(file, err) {
227
+ if (err instanceof SecretFileError)
228
+ return err;
229
+ const code = err.code;
230
+ if (code === 'ENOENT')
231
+ return new SecretFileError(`${file} cannot be written because a parent directory is missing. Create the account with \`sideby new <family> <name> --api\`, then run \`sideby key\` again.`);
232
+ if (code === 'EACCES' || code === 'EPERM')
233
+ return new SecretFileError(`${file} cannot be written (permission denied). Make the account directory yours, then run \`sideby key\` again.`);
234
+ return new SecretFileError(`${file} could not be written. Check that the account directory is a real folder you can write to, then run \`sideby key\` again.`);
235
+ }