sideby 0.17.0 → 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 (95) hide show
  1. package/README.md +3 -1
  2. package/ai-tasks.json +90 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +9 -1
  5. package/dist/src/cli/commands.js +349 -14
  6. package/dist/src/cli/json-schemas.js +157 -18
  7. package/dist/src/cli/main.js +56 -7
  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 +73 -1
  11. package/dist/src/core/ask.js +106 -6
  12. package/dist/src/core/autostart.d.ts +38 -8
  13. package/dist/src/core/autostart.js +85 -39
  14. package/dist/src/core/brand-mark.d.ts +49 -11
  15. package/dist/src/core/brand-mark.js +116 -38
  16. package/dist/src/core/config.d.ts +5 -0
  17. package/dist/src/core/config.js +11 -1
  18. package/dist/src/core/desktop-app.d.ts +1 -1
  19. package/dist/src/core/desktop-app.js +2 -2
  20. package/dist/src/core/edit-settings.d.ts +24 -0
  21. package/dist/src/core/edit-settings.js +97 -0
  22. package/dist/src/core/handoff-brief.d.ts +4 -2
  23. package/dist/src/core/handoff-brief.js +6 -1
  24. package/dist/src/core/handoff-chain.d.ts +24 -0
  25. package/dist/src/core/handoff-chain.js +2 -0
  26. package/dist/src/core/handoff-run.d.ts +4 -3
  27. package/dist/src/core/handoff-run.js +14 -9
  28. package/dist/src/core/launch.d.ts +2 -0
  29. package/dist/src/core/launch.js +14 -10
  30. package/dist/src/core/local-build.d.ts +12 -5
  31. package/dist/src/core/local-build.js +49 -31
  32. package/dist/src/core/lock.d.ts +30 -0
  33. package/dist/src/core/lock.js +143 -0
  34. package/dist/src/core/quota-levels.d.ts +6 -1
  35. package/dist/src/core/quota-levels.js +16 -5
  36. package/dist/src/core/task-spec.d.ts +95 -0
  37. package/dist/src/core/task-spec.js +209 -0
  38. package/dist/src/core/terminal.js +6 -1
  39. package/dist/src/core/update.d.ts +27 -16
  40. package/dist/src/core/update.js +67 -93
  41. package/dist/src/desktop/icon.js +12 -15
  42. package/dist/src/families/claude/ai-task.d.ts +8 -0
  43. package/dist/src/families/claude/ai-task.js +38 -0
  44. package/dist/src/families/claude/handoff-hook.js +4 -4
  45. package/dist/src/families/claude/index.js +3 -0
  46. package/dist/src/families/codex/handoff-hook.js +4 -4
  47. package/dist/src/families/codex/index.js +9 -0
  48. package/dist/src/families/grok/handoff-hook.js +4 -4
  49. package/dist/src/families/grok/index.js +1 -0
  50. package/dist/src/families/pi/index.js +1 -0
  51. package/dist/src/handoff/hook.js +51 -30
  52. package/dist/src/handoff/levels.d.ts +24 -0
  53. package/dist/src/handoff/levels.js +70 -0
  54. package/dist/src/handoff/messages.d.ts +6 -3
  55. package/dist/src/handoff/messages.js +20 -7
  56. package/dist/src/handoff/reader.d.ts +6 -3
  57. package/dist/src/menubar/agent.d.ts +3 -0
  58. package/dist/src/menubar/agent.js +21 -0
  59. package/dist/src/menubar/script.d.ts +8 -0
  60. package/dist/src/menubar/script.js +457 -0
  61. package/dist/src/menubar/snapshot.d.ts +115 -0
  62. package/dist/src/menubar/snapshot.js +255 -0
  63. package/dist/src/menubar/strings.d.ts +87 -0
  64. package/dist/src/menubar/strings.js +88 -0
  65. package/dist/src/panel/background.js +12 -19
  66. package/dist/src/panel/handler.d.ts +12 -0
  67. package/dist/src/panel/handler.js +80 -80
  68. package/dist/src/panel/i18n.d.ts +33 -0
  69. package/dist/src/panel/i18n.js +66 -0
  70. package/dist/src/panel/page-logic.d.ts +105 -0
  71. package/dist/src/panel/page-logic.js +170 -15
  72. package/dist/src/panel/page-script.js +238 -109
  73. package/dist/src/panel/page-styles.js +42 -13
  74. package/dist/src/panel/page.d.ts +7 -0
  75. package/dist/src/panel/page.js +5 -0
  76. package/dist/src/runtime.d.ts +9 -1
  77. package/dist/src/runtime.js +11 -3
  78. package/dist/src/types.d.ts +14 -0
  79. package/package.json +4 -3
  80. package/schemas/ask-choices.json +168 -0
  81. package/schemas/ask-print.json +87 -0
  82. package/schemas/config.json +17 -1
  83. package/schemas/edit.json +119 -0
  84. package/schemas/error.json +4 -0
  85. package/schemas/families.json +4 -0
  86. package/schemas/list.json +4 -0
  87. package/schemas/local.json +1 -1
  88. package/schemas/menubar-snapshot.json +646 -0
  89. package/schemas/menubar-start.json +112 -0
  90. package/schemas/menubar.json +165 -0
  91. package/skills/sideby/SKILL.md +6 -2
  92. package/skills/sideby/references/ai-tasks.md +10 -0
  93. package/skills/sideby/references/handoff.md +3 -1
  94. package/skills/sideby/references/panel.md +6 -0
  95. package/skills/sideby/references/update.md +1 -1
@@ -88,15 +88,17 @@ export function launchCommand(opts) {
88
88
  const keep = opts.title && family.keepTitle && !opts.userArgs.some((a) => a.includes(family.keepTitle.key))
89
89
  ? family.keepTitle.args
90
90
  : [];
91
- return {
92
- bin: family.bin,
93
- args: [
94
- ...(family.defaultArgs?.(account, opts.userArgs) ?? []),
95
- ...keep,
96
- ...opts.accountArgs,
97
- ...opts.userArgs,
98
- ],
99
- };
91
+ const args = [
92
+ ...(family.defaultArgs?.(account, opts.userArgs) ?? []),
93
+ ...keep,
94
+ ...opts.accountArgs,
95
+ ...opts.userArgs,
96
+ ];
97
+ return { bin: family.bin, args: opts.aiTask ? aiTaskArgs(family, args) : args };
98
+ }
99
+ /** The arguments of an AI Task's Launch, without the Family's permission bypasses (ADR-0031). */
100
+ function aiTaskArgs(family, args) {
101
+ return family.aiTaskArgs ? family.aiTaskArgs(args) : args;
100
102
  }
101
103
  export async function prepareLaunch(opts) {
102
104
  const { account, family } = opts;
@@ -119,6 +121,8 @@ export async function prepareLaunch(opts) {
119
121
  config: {},
120
122
  command: opts.command,
121
123
  });
124
+ // A `launch.before` hook cannot add a bypass back into an AI Task either.
125
+ const finalArgs = opts.aiTask && opts.command === 'run' ? aiTaskArgs(family, args) : args;
122
126
  // Control characters would end the escape sequence early; labels are shell-safe names, so this is a guard only.
123
127
  const title = opts.title
124
128
  ? [...`[${env.SIDEBY_LABEL ?? account.ref}]`].filter((ch) => ch >= ' ' && ch !== '\x7f').join('')
@@ -127,7 +131,7 @@ export async function prepareLaunch(opts) {
127
131
  account,
128
132
  family,
129
133
  bin: family.bin,
130
- args,
134
+ args: finalArgs,
131
135
  env,
132
136
  ...(notice ? { notice } : {}),
133
137
  ...(title ? { title } : {}),
@@ -11,6 +11,12 @@ export interface LocalDirs {
11
11
  export declare const pkgDir: (d: LocalDirs) => string;
12
12
  export declare const globalPkg: (d: LocalDirs) => string;
13
13
  export declare const devDir: (env: Env) => string;
14
+ /**
15
+ * The environment to ask npm for its global prefix in. A pnpm script gets pnpm's own `--dir` (`pnpm -C <dir> …`) as
16
+ * `npm_config_dir` and `npm_config_prefix`, and npm would answer with that directory; npm reads the user's real
17
+ * setting from its config files and from `NPM_CONFIG_PREFIX` without them.
18
+ */
19
+ export declare function npmEnv(env: Env): Env;
14
20
  /** Where the switch works, with npm's global prefix from `npm prefix -g`; null when npm cannot be asked. */
15
21
  export declare function localDirs(env: Env): Promise<LocalDirs | null>;
16
22
  export declare function kind(p: string): Promise<'link' | 'dir' | 'file' | null>;
@@ -51,11 +57,11 @@ export interface SwitchResult {
51
57
  unchanged?: boolean;
52
58
  restartedPanel: boolean;
53
59
  /**
54
- * Back on npm, `sideby update --yes` of the npm code brought the skill agents read to its version (true), or that
55
- * failed (false); absent for a switch to the Local Build, which has no skill of its own to bring.
60
+ * Back on npm, `sideby update --skill --yes` of the npm code brought the skill agents read to its version (true), or
61
+ * that failed (false); absent for a switch to the Local Build, which has no skill of its own to bring.
56
62
  */
57
63
  skillSynced?: boolean;
58
- /** With `skillSync: 'background'`: that `sideby update --yes` started on its own and is not waited for. */
64
+ /** With `skillSync: 'background'`: that `sideby update --skill --yes` started on its own and is not waited for. */
59
65
  skillSyncStarted?: boolean;
60
66
  /** Another install held the lock; nothing ran. */
61
67
  busy?: boolean;
@@ -64,8 +70,9 @@ export interface SwitchResult {
64
70
  }
65
71
  /**
66
72
  * Puts `to` behind the global `sideby`. `local` links the newest Local Build; `npm` restores the kept package or
67
- * installs `latest` (a failed install links the Local Build back, so `sideby` never goes missing). Afterwards a
68
- * background Panel on `panelPort` starts again from the new code. One install at a time (the Update lock).
73
+ * installs `latest` (a failed install links the Local Build back, so `sideby` never goes missing). Afterwards
74
+ * (after-install.ts) an existing login item follows, back on npm the skill does, and a background Panel on `panelPort`
75
+ * starts again from the new code, last. One install at a time (the Update lock).
69
76
  */
70
77
  export declare function switchLocal(paths: Paths, d: LocalDirs, to: LocalTarget, env: Env, opts?: {
71
78
  panelPort?: () => Promise<number | null>;
@@ -5,17 +5,30 @@
5
5
  import { lstat, mkdir, readFile, readlink, realpath, rename, rm, symlink } from 'node:fs/promises';
6
6
  import { homedir } from 'node:os';
7
7
  import { dirname, join, relative } from 'node:path';
8
+ import { MENUBAR_AGENT } from '../menubar/agent.js';
9
+ import { afterInstall } from './after-install.js';
8
10
  import { refreshAutostart } from './autostart.js';
9
- import { compareVersions, fetchLatest, restartPanelByName, runProgram, startDetached, takeInstallLock, } from './update.js';
11
+ import { compareVersions, fetchLatest, runProgram, takeInstallLock, updateMachine } from './update.js';
10
12
  import { parseLocalBuild } from './version.js';
11
13
  const BIN = 'dist/src/cli/main.js';
12
14
  export const pkgDir = (d) => join(d.dev, 'pkg');
13
15
  export const globalPkg = (d) => join(d.prefix, 'lib', 'node_modules', 'sideby');
14
16
  const globalBin = (d) => join(d.prefix, 'bin', 'sideby');
15
17
  export const devDir = (env) => join(env.XDG_DATA_HOME || join(env.HOME || homedir(), '.local', 'share'), 'sideby-dev');
18
+ /**
19
+ * The environment to ask npm for its global prefix in. A pnpm script gets pnpm's own `--dir` (`pnpm -C <dir> …`) as
20
+ * `npm_config_dir` and `npm_config_prefix`, and npm would answer with that directory; npm reads the user's real
21
+ * setting from its config files and from `NPM_CONFIG_PREFIX` without them.
22
+ */
23
+ export function npmEnv(env) {
24
+ if (!env.npm_config_user_agent?.startsWith('pnpm/'))
25
+ return env;
26
+ const { npm_config_prefix: _prefix, npm_config_dir: _dir, ...rest } = env;
27
+ return rest;
28
+ }
16
29
  /** Where the switch works, with npm's global prefix from `npm prefix -g`; null when npm cannot be asked. */
17
30
  export async function localDirs(env) {
18
- const r = await runProgram('npm', ['prefix', '-g'], { env }).catch(() => null);
31
+ const r = await runProgram('npm', ['prefix', '-g'], { env: npmEnv(env) }).catch(() => null);
19
32
  const prefix = r && r.code === 0 ? r.output.trim().split('\n').at(-1)?.trim() : '';
20
33
  return prefix ? { dev: devDir(env), prefix } : null;
21
34
  }
@@ -131,17 +144,17 @@ async function refreshLoginItem(paths, d, ctx = {}) {
131
144
  const entry = await realpath(join(globalPkg(d), BIN)).catch(() => null);
132
145
  if (!entry)
133
146
  return undefined;
134
- const r = await refreshAutostart({
135
- home: paths.home,
136
- launcher: { node: process.execPath, entry },
137
- ...ctx,
138
- });
147
+ const agentCtx = { home: paths.home, launcher: { node: process.execPath, entry }, ...ctx };
148
+ // The menu bar item (ADR-0034) records the same Node and entry; it is reported nowhere, like a failure here.
149
+ await refreshAutostart(agentCtx, MENUBAR_AGENT);
150
+ const r = await refreshAutostart(agentCtx);
139
151
  return r.state === 'on' || r.state === 'stale' ? r.rewritten : undefined;
140
152
  }
141
153
  /**
142
154
  * Puts `to` behind the global `sideby`. `local` links the newest Local Build; `npm` restores the kept package or
143
- * installs `latest` (a failed install links the Local Build back, so `sideby` never goes missing). Afterwards a
144
- * background Panel on `panelPort` starts again from the new code. One install at a time (the Update lock).
155
+ * installs `latest` (a failed install links the Local Build back, so `sideby` never goes missing). Afterwards
156
+ * (after-install.ts) an existing login item follows, back on npm the skill does, and a background Panel on `panelPort`
157
+ * starts again from the new code, last. One install at a time (the Update lock).
145
158
  */
146
159
  export async function switchLocal(paths, d, to, env, opts = {}) {
147
160
  const before = await localStatus(d);
@@ -168,6 +181,13 @@ export async function switchLocal(paths, d, to, env, opts = {}) {
168
181
  const release = await takeInstallLock(paths);
169
182
  if (!release)
170
183
  return fail('a sideby update is running; wait for it to finish, then switch again', { busy: true });
184
+ let released = false;
185
+ const free = async () => {
186
+ if (released)
187
+ return;
188
+ released = true;
189
+ await release().catch(() => { });
190
+ };
171
191
  let message;
172
192
  try {
173
193
  if (to === 'local') {
@@ -195,31 +215,29 @@ export async function switchLocal(paths, d, to, env, opts = {}) {
195
215
  message = `the global sideby runs the npm package ${want}`;
196
216
  }
197
217
  }
198
- }
199
- finally {
200
- await release().catch(() => { });
201
- }
202
- // The login item records the sideby it starts, like `sideby update` keeps it pointing at the one in use.
203
- const refreshed = await refreshLoginItem(paths, d, opts.autostart);
204
- const login = refreshed === undefined ? {} : { refreshedAutostart: refreshed };
205
- const port = opts.panelPort ? await opts.panelPort().catch(() => null) : null;
206
- const restartedPanel = port !== null && (await restartPanelByName(env, port));
207
- if (to === 'local')
208
- return { ok: true, message, running: to, restartedPanel, ...login };
209
- // The skill is part of the version (spec §3.23): the npm code updates it as `sideby update --yes` does for anyone,
210
- // by name so the new code runs, after the lock above is free. A failure keeps the switch.
211
- if (opts.skillSync === 'background')
218
+ // The login item records the sideby it starts, like `sideby update` keeps it pointing at the one in use. Back on
219
+ // npm the skill is part of the version (spec §3.23): the npm code updates it alone, by name so the new code runs,
220
+ // after the lock is free. A failure there keeps the switch.
221
+ const after = await afterInstall(updateMachine(), env, {
222
+ home: paths.home,
223
+ release: free,
224
+ autostart: () => refreshLoginItem(paths, d, opts.autostart),
225
+ ...(to === 'npm' ? { skill: 'by-name' } : {}),
226
+ ...(opts.skillSync ? { skillSync: opts.skillSync } : {}),
227
+ ...(opts.panelPort ? { panelPort: opts.panelPort } : {}),
228
+ ...(opts.onOutput ? { onOutput: opts.onOutput } : {}),
229
+ });
212
230
  return {
213
231
  ok: true,
214
232
  message,
215
233
  running: to,
216
- restartedPanel,
217
- ...login,
218
- skillSyncStarted: await startDetached('sideby', ['update', '--yes'], env),
234
+ restartedPanel: after.restartedPanel,
235
+ ...(after.refreshedAutostart === undefined ? {} : { refreshedAutostart: after.refreshedAutostart }),
236
+ ...(after.skillSynced === undefined ? {} : { skillSynced: after.skillSynced }),
237
+ ...(after.skillSyncStarted === undefined ? {} : { skillSyncStarted: after.skillSyncStarted }),
219
238
  };
220
- const u = await runProgram('sideby', ['update', '--yes'], {
221
- env,
222
- ...(opts.onOutput ? { onOutput: opts.onOutput } : {}),
223
- }).catch(() => ({ code: 1, output: '' }));
224
- return { ok: true, message, running: to, restartedPanel, ...login, skillSynced: u.code === 0 };
239
+ }
240
+ finally {
241
+ await free();
242
+ }
225
243
  }
@@ -0,0 +1,30 @@
1
+ export interface FileLockOptions {
2
+ /** A lock its holder has not touched for this long is free, whether or not its pid runs. */
3
+ staleMs: number;
4
+ /** How often the holder touches its lock. Keep it well under `staleMs`. */
5
+ beatMs: number;
6
+ /** A lock older than this is free even when touched: its pid may since belong to another process. Default: none. */
7
+ maxMs?: number;
8
+ /** How long an empty or unreadable lock counts as held (its owner may still be writing it). Default: `staleMs`. */
9
+ writeGraceMs?: number;
10
+ /** Whether a pid runs. Default: `processAlive`. */
11
+ alive?: (pid: number) => boolean;
12
+ /** Milliseconds since epoch, for the lock's content and its age. Default: `Date.now`. */
13
+ now?: () => number;
14
+ /** Wait for a held lock, checking every `pollMs`, up to `timeoutMs`. Without it a held lock gives null at once. */
15
+ wait?: {
16
+ timeoutMs: number;
17
+ pollMs: number;
18
+ };
19
+ }
20
+ /** Stops the heartbeat and removes the lock, only while it still holds this holder's content. */
21
+ export type ReleaseLock = () => Promise<void>;
22
+ /** Whether a Linux `/proc/<pid>/stat` line is of a zombie: the state after the parenthesised command name is `Z`. */
23
+ export declare function isZombieStat(line: string): boolean;
24
+ /** Whether `pid` runs. A zombie (exited, nobody waited for it) answers signal 0 on Linux but holds nothing. */
25
+ export declare function processAlive(pid: number): boolean;
26
+ /**
27
+ * Takes the lock `file` (its directory must exist). Returns its release function, or null when another holder keeps
28
+ * it (after waiting, with `wait`). Errors other than the file existing are thrown.
29
+ */
30
+ export declare function takeFileLock(file: string, opts: FileLockOptions): Promise<ReleaseLock | null>;
@@ -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
+ }
@@ -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
  }
@@ -0,0 +1,95 @@
1
+ import type { Runtime } from '../runtime.ts';
2
+ import { type AiTaskInput } from './ask.ts';
3
+ import { type Attachment } from './attachments.ts';
4
+ import { UserError } from './errors.ts';
5
+ /** The largest Task Spec read from stdin. */
6
+ export declare const MAX_SPEC_BYTES: number;
7
+ /** The Task Spec version this sideby understands; a Portal that sends another one is told to update sideby. */
8
+ export declare const SPEC_VERSION = 1;
9
+ /** Why a Task Spec was refused; `spec-version` exits 2 so a Portal can tell "update sideby" apart. */
10
+ export type SpecErrorCode = 'spec-invalid' | 'spec-too-large' | 'spec-version' | 'bad-cwd';
11
+ export declare class SpecError extends UserError {
12
+ readonly code: SpecErrorCode;
13
+ constructor(code: SpecErrorCode, message: string);
14
+ }
15
+ interface SpecCommon {
16
+ lang?: 'en' | 'zh';
17
+ account?: string;
18
+ terminal?: string;
19
+ remember?: boolean;
20
+ files?: string[];
21
+ }
22
+ export type TaskSpec = (SpecCommon & {
23
+ prompt: string;
24
+ cwd?: string;
25
+ }) | (SpecCommon & {
26
+ native: {
27
+ task: string;
28
+ text?: string;
29
+ context?: AiTaskInput['context'];
30
+ };
31
+ });
32
+ /** Reads a Task Spec from `input` (stdin), refusing more than MAX_SPEC_BYTES before it is all read. */
33
+ export declare function readSpecText(input: AsyncIterable<Buffer | string>): Promise<string>;
34
+ /** Checks a Task Spec's shape. Values are kept as given; `cwd` is checked later against the HOME. */
35
+ export declare function parseTaskSpec(text: string): TaskSpec;
36
+ /**
37
+ * The folder a Task Spec's prompt starts in: an existing directory inside the HOME, as its real path. Without one,
38
+ * sideby's own task work folder (`"cwd": "engine"` in a Tool's declaration).
39
+ */
40
+ export declare function specCwd(rt: Runtime, cwd: string | undefined): Promise<string | undefined>;
41
+ /** `sideby ask --spec - --print`: the prompt the Host would get, without writing a task or copying a file. */
42
+ export declare function previewTaskSpec(rt: Runtime, spec: TaskSpec): Promise<{
43
+ schemaVersion: 1;
44
+ prompt: string;
45
+ removedSecrets: boolean;
46
+ }>;
47
+ /** `sideby ask --spec -`: starts the AI Task the spec describes; the result is `startAiTask`'s. */
48
+ export declare function startTaskSpec(rt: Runtime, spec: TaskSpec): Promise<{
49
+ schemaVersion: 1;
50
+ task: null;
51
+ account: null;
52
+ terminal: null;
53
+ opened: boolean;
54
+ command: null;
55
+ prompt: string;
56
+ reason: import("./ask.ts").AiTaskReason;
57
+ detail: string;
58
+ removedSecrets: boolean;
59
+ attachments: Attachment[];
60
+ } | {
61
+ schemaVersion: 1;
62
+ task: string;
63
+ account: string;
64
+ terminal: string;
65
+ opened: boolean;
66
+ command: string;
67
+ reason?: import("./ask.ts").AiTaskReason | undefined;
68
+ detail?: string | undefined;
69
+ prompt?: undefined;
70
+ removedSecrets: boolean;
71
+ attachments: Attachment[];
72
+ }>;
73
+ /**
74
+ * `sideby ask --choices` (ADR-0030): what a Portal's dialog offers before it starts a task. `account` is what an AI
75
+ * Task would pick now (null with `reason` and `detail` when nothing can be picked); `accounts` lists every API
76
+ * Account and Subscription Account, signed-in ones first; `terminals` the supported terminals installed here, with
77
+ * the one a task would open in `terminal`.
78
+ */
79
+ export declare function taskChoices(rt: Runtime): Promise<{
80
+ schemaVersion: 1;
81
+ account: string | null;
82
+ accounts: {
83
+ ref: string;
84
+ label: string;
85
+ signedIn: boolean;
86
+ }[];
87
+ terminal: import("./terminal.ts").TerminalId;
88
+ terminals: {
89
+ id: import("./terminal.ts").TerminalId;
90
+ label: string;
91
+ }[];
92
+ reason: "all-full" | "no-accounts" | "none-signed-in" | null;
93
+ detail: string | null;
94
+ }>;
95
+ export {};