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
@@ -0,0 +1,209 @@
1
+ // Task Specs (spec §3.28 "Portal 交来的任务", ADR-0030): a Portal hands sideby an AI Task as one JSON object on
2
+ // stdin, either a Task Prompt it wrote for another Tool or one of sideby's own tasks (`native`). sideby picks the
3
+ // Account, takes the attachments and opens the Preferred Terminal exactly as for its own AI Tasks; the prompt reaches
4
+ // the Host only through the task file, never a shell.
5
+ import { isAbsolute } from 'node:path';
6
+ import { AI_TASK_KINDS, attachedSection, stripSecrets } from '../panel/page-logic.js';
7
+ import { newTaskId, openPromptTask, PICK_DETAIL, pickTaskAccount, previewAttachments, promptForTask, realCwdInHome, startAiTask, taskContext, taskLang, terminals, } from './ask.js';
8
+ import { checkAttachmentFiles, copyAttachments, MAX_ATTACHMENTS } from './attachments.js';
9
+ import { UserError } from './errors.js';
10
+ import { TERMINALS } from './terminal.js';
11
+ /** The largest Task Spec read from stdin. */
12
+ export const MAX_SPEC_BYTES = 1024 * 1024;
13
+ /** The Task Spec version this sideby understands; a Portal that sends another one is told to update sideby. */
14
+ export const SPEC_VERSION = 1;
15
+ export class SpecError extends UserError {
16
+ code;
17
+ constructor(code, message) {
18
+ super(message, { code });
19
+ this.code = code;
20
+ }
21
+ }
22
+ const invalid = (message) => new SpecError('spec-invalid', `${message}; fix the Task Spec and send it again.`);
23
+ const COMMON = ['specVersion', 'lang', 'account', 'terminal', 'remember', 'files'];
24
+ /** Reads a Task Spec from `input` (stdin), refusing more than MAX_SPEC_BYTES before it is all read. */
25
+ export async function readSpecText(input) {
26
+ const chunks = [];
27
+ let size = 0;
28
+ for await (const chunk of input) {
29
+ const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
30
+ size += buf.length;
31
+ if (size > MAX_SPEC_BYTES)
32
+ throw new SpecError('spec-too-large', `The Task Spec is larger than ${MAX_SPEC_BYTES} bytes; attach big content as files instead.`);
33
+ chunks.push(buf);
34
+ }
35
+ return Buffer.concat(chunks).toString('utf8');
36
+ }
37
+ /** Checks a Task Spec's shape. Values are kept as given; `cwd` is checked later against the HOME. */
38
+ export function parseTaskSpec(text) {
39
+ let raw;
40
+ try {
41
+ raw = JSON.parse(text);
42
+ }
43
+ catch {
44
+ throw invalid('The Task Spec is not valid JSON');
45
+ }
46
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
47
+ throw invalid('The Task Spec must be one JSON object');
48
+ const o = raw;
49
+ if (o.specVersion !== SPEC_VERSION) {
50
+ if (typeof o.specVersion === 'number')
51
+ throw new SpecError('spec-version', `This sideby reads Task Spec version ${SPEC_VERSION}, not ${o.specVersion}; update sideby with \`sideby update\`.`);
52
+ throw invalid(`"specVersion" must be ${SPEC_VERSION}`);
53
+ }
54
+ const hasPrompt = o.prompt !== undefined;
55
+ const hasNative = o.native !== undefined;
56
+ if (hasPrompt === hasNative)
57
+ throw invalid('Give either "prompt" (with "cwd") or "native", not both or neither');
58
+ const allowed = new Set([...COMMON, ...(hasPrompt ? ['prompt', 'cwd'] : ['native'])]);
59
+ for (const k of Object.keys(o))
60
+ if (!allowed.has(k))
61
+ throw invalid(`Unknown field "${k}"`);
62
+ const common = {};
63
+ if (o.lang !== undefined && o.lang !== null) {
64
+ if (o.lang !== 'en' && o.lang !== 'zh')
65
+ throw invalid('"lang" must be "en" or "zh"');
66
+ common.lang = o.lang;
67
+ }
68
+ for (const key of ['account', 'terminal']) {
69
+ const v = o[key];
70
+ if (v === undefined || v === null)
71
+ continue;
72
+ if (typeof v !== 'string' || !v)
73
+ throw invalid(`"${key}" must be a string or null`);
74
+ common[key] = v;
75
+ }
76
+ if (common.terminal && !TERMINALS.some((t) => t.id === common.terminal))
77
+ throw invalid(`"terminal" must be one of ${TERMINALS.map((t) => t.id).join(', ')}`);
78
+ if (o.remember !== undefined && o.remember !== null) {
79
+ if (typeof o.remember !== 'boolean')
80
+ throw invalid('"remember" must be true or false');
81
+ common.remember = o.remember;
82
+ }
83
+ if (o.files !== undefined && o.files !== null) {
84
+ const f = o.files;
85
+ if (!Array.isArray(f) ||
86
+ f.length > MAX_ATTACHMENTS ||
87
+ !f.every((p) => typeof p === 'string' && isAbsolute(p) && !p.includes('\0')))
88
+ throw invalid(`"files" must list at most ${MAX_ATTACHMENTS} absolute paths`);
89
+ if (f.length)
90
+ common.files = f;
91
+ }
92
+ if (hasPrompt) {
93
+ if (typeof o.prompt !== 'string' || !o.prompt.trim())
94
+ throw invalid('"prompt" must be a non-empty string');
95
+ if (o.cwd !== undefined && o.cwd !== null && typeof o.cwd !== 'string')
96
+ throw invalid('"cwd" must be a path');
97
+ return { ...common, prompt: o.prompt, ...(typeof o.cwd === 'string' ? { cwd: o.cwd } : {}) };
98
+ }
99
+ const n = o.native;
100
+ if (!n || typeof n !== 'object' || Array.isArray(n))
101
+ throw invalid('"native" must be an object');
102
+ const native = n;
103
+ for (const k of Object.keys(native))
104
+ if (!['task', 'text', 'context'].includes(k))
105
+ throw invalid(`Unknown field "native.${k}"`);
106
+ if (typeof native.task !== 'string' || !AI_TASK_KINDS.includes(native.task))
107
+ throw invalid(`"native.task" must be one of ${AI_TASK_KINDS.join(', ')}`);
108
+ if (native.text !== undefined && native.text !== null && typeof native.text !== 'string')
109
+ throw invalid('"native.text" must be a string');
110
+ const context = taskContext(native.context, (m) => invalid(m.replace('"context', '"native.context')));
111
+ return {
112
+ ...common,
113
+ native: {
114
+ task: native.task,
115
+ ...(typeof native.text === 'string' && native.text ? { text: native.text } : {}),
116
+ ...(context ? { context } : {}),
117
+ },
118
+ };
119
+ }
120
+ /**
121
+ * The folder a Task Spec's prompt starts in: an existing directory inside the HOME, as its real path. Without one,
122
+ * sideby's own task work folder (`"cwd": "engine"` in a Tool's declaration).
123
+ */
124
+ export async function specCwd(rt, cwd) {
125
+ if (cwd === undefined)
126
+ return undefined;
127
+ const bad = (why) => new SpecError('bad-cwd', `The task folder ${JSON.stringify(cwd)} ${why}; name an existing folder in your home.`);
128
+ const checked = await realCwdInHome(cwd, rt.paths.home);
129
+ if ('why' in checked)
130
+ throw bad(checked.why);
131
+ return checked.real;
132
+ }
133
+ function nativeInput(spec) {
134
+ return {
135
+ task: spec.native.task,
136
+ ...(spec.native.text ? { text: spec.native.text } : {}),
137
+ ...(spec.native.context ? { context: spec.native.context } : {}),
138
+ ...(spec.lang ? { lang: spec.lang } : {}),
139
+ ...(spec.account ? { account: spec.account } : {}),
140
+ ...(spec.terminal ? { terminal: spec.terminal } : {}),
141
+ ...(spec.remember ? { remember: spec.remember } : {}),
142
+ ...(spec.files ? { files: spec.files } : {}),
143
+ };
144
+ }
145
+ /** A Portal's prompt as the Host gets it: keys removed again, then the attachments section at its heading level. */
146
+ function specPrompt(rt, spec, attachments) {
147
+ const cleaned = stripSecrets(spec.prompt);
148
+ const heading = /^(#{1,6} )\S/m.exec(cleaned.text)?.[1] ?? '';
149
+ const files = attachments.map(({ path, kind }) => ({ path, kind }));
150
+ const section = attachedSection(files, taskLang(rt, spec.lang), heading);
151
+ return {
152
+ prompt: section ? `${cleaned.text.trimEnd()}\n\n${section}` : cleaned.text,
153
+ removedSecrets: cleaned.removed,
154
+ };
155
+ }
156
+ /** `sideby ask --spec - --print`: the prompt the Host would get, without writing a task or copying a file. */
157
+ export async function previewTaskSpec(rt, spec) {
158
+ if ('native' in spec) {
159
+ const input = nativeInput(spec);
160
+ const { prompt, removedSecrets } = promptForTask(rt, input, await previewAttachments(rt, input));
161
+ return { schemaVersion: 1, prompt, removedSecrets };
162
+ }
163
+ await specCwd(rt, spec.cwd);
164
+ const files = spec.files ? await checkAttachmentFiles(spec.files) : [];
165
+ return { schemaVersion: 1, ...specPrompt(rt, spec, files) };
166
+ }
167
+ /** `sideby ask --spec -`: starts the AI Task the spec describes; the result is `startAiTask`'s. */
168
+ export async function startTaskSpec(rt, spec) {
169
+ if ('native' in spec)
170
+ return startAiTask(rt, nativeInput(spec));
171
+ // The folder is checked before any attachment is copied.
172
+ const cwd = await specCwd(rt, spec.cwd);
173
+ const taskId = newTaskId();
174
+ const attachments = spec.files ? await copyAttachments(rt.paths, spec.files, taskId) : [];
175
+ const written = specPrompt(rt, spec, attachments);
176
+ return openPromptTask(rt, spec, { taskId, ...written, attachments, ...(cwd ? { cwd } : {}) });
177
+ }
178
+ /**
179
+ * `sideby ask --choices` (ADR-0030): what a Portal's dialog offers before it starts a task. `account` is what an AI
180
+ * Task would pick now (null with `reason` and `detail` when nothing can be picked); `accounts` lists every API
181
+ * Account and Subscription Account, signed-in ones first; `terminals` the supported terminals installed here, with
182
+ * the one a task would open in `terminal`.
183
+ */
184
+ export async function taskChoices(rt) {
185
+ const pick = await pickTaskAccount(rt);
186
+ const signedIn = [];
187
+ const api = [];
188
+ const signedOut = [];
189
+ const all = [...(await rt.accounts())].sort((a, b) => (a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0));
190
+ for (const a of all) {
191
+ if (a.kind === 'api')
192
+ api.push({ ref: a.ref, label: `${a.ref} · API`, signedIn: true });
193
+ else if ((await rt.status(a)).login === 'logged-in')
194
+ signedIn.push({ ref: a.ref, label: a.ref, signedIn: true });
195
+ else
196
+ signedOut.push({ ref: a.ref, label: a.ref, signedIn: false });
197
+ }
198
+ const t = await terminals(rt);
199
+ const name = (id) => TERMINALS.find((x) => x.id === id)?.name ?? id;
200
+ return {
201
+ schemaVersion: 1,
202
+ account: 'account' in pick ? pick.account.ref : null,
203
+ accounts: [...signedIn, ...api, ...signedOut],
204
+ terminal: t.guess.id,
205
+ terminals: t.installed.map((i) => ({ id: i.id, label: name(i.id) })),
206
+ reason: 'reason' in pick ? pick.reason : null,
207
+ detail: 'reason' in pick ? PICK_DETAIL[pick.reason] : null,
208
+ };
209
+ }
@@ -350,8 +350,13 @@ export async function openTerminal(id, opts, exec) {
350
350
  try {
351
351
  const launch = launchArgs(id, { ...opts, ...installed });
352
352
  const result = await exec(launch.file, launch.args);
353
- if (result.code === 0)
353
+ if (result.code === 0) {
354
+ // `orca terminal create --focus` only switches tabs inside Orca; bring its window to the front too.
355
+ const bundleId = id === 'orca' ? TERMINALS.find((t) => t.id === 'orca')?.bundleId : null;
356
+ if (bundleId)
357
+ await exec('/usr/bin/open', ['-b', bundleId]).catch(() => undefined);
354
358
  return { ok: true };
359
+ }
355
360
  if (launch.file === '/usr/bin/osascript' &&
356
361
  (result.code === -1743 || /-1743|Not authorized to send Apple events/i.test(result.stderr)))
357
362
  return {
@@ -1,5 +1,6 @@
1
1
  import type { Env } from '../types.ts';
2
2
  import type { Paths } from './paths.ts';
3
+ export { isZombieStat } from './lock.ts';
3
4
  export declare const DEFAULT_REGISTRY = "https://registry.npmjs.org";
4
5
  export declare const CHECK_INTERVAL_MS: number;
5
6
  export declare const NOTICE_INTERVAL_MS: number;
@@ -66,8 +67,6 @@ export interface InstallMethod {
66
67
  /** npm only: the prefix whose `lib/node_modules` holds sideby. */
67
68
  prefix?: string;
68
69
  }
69
- /** Whether a Linux `/proc/<pid>/stat` line is of a zombie: the state after the parenthesised command name is `Z`. */
70
- export declare function isZombieStat(stat: string): boolean;
71
70
  /** Swapped in tests through `bindUpdateDeps`; the real machine otherwise. */
72
71
  /**
73
72
  * Whether `sideby autostart --refresh --json` rewrote the login item: it exits 0 also when nothing changed or the
@@ -97,19 +96,22 @@ export interface UpdateDeps {
97
96
  appInstalled: (home: string, env: Env) => Promise<boolean>;
98
97
  /** Runs `sideby app install --json` from the newly installed code and waits; false when it failed. */
99
98
  refreshApp: (env: Env) => Promise<boolean>;
100
- /** Whether `sideby autostart on` put a login item in this home (its file carries the sideby marker). */
101
- autostartInstalled: (home: string) => Promise<boolean>;
102
- /** Runs `sideby autostart --refresh --json` from the newly installed code and waits; false when it failed. */
103
- refreshAutostart: (env: Env) => Promise<boolean>;
99
+ /**
100
+ * Whether `sideby autostart on` (or `sideby menubar on`, ADR-0034) put its login item in this home (its file carries
101
+ * the sideby marker).
102
+ */
103
+ autostartInstalled: (home: string, command?: LoginItemCommand) => Promise<boolean>;
104
+ /** Runs `sideby <command> --refresh --json` from the newly installed code and waits; false when it failed. */
105
+ refreshAutostart: (env: Env, command?: LoginItemCommand) => Promise<boolean>;
104
106
  }
107
+ /** The commands whose login item records the sideby it starts. */
108
+ export type LoginItemCommand = 'autostart' | 'menubar';
105
109
  /** Internal, for tests: replaces parts of the machine. Not part of the plugin or Portal contract. */
106
110
  export declare function bindUpdateDeps(deps: Partial<UpdateDeps>): () => void;
107
111
  /** Runs a program through the swappable machine (tests bind `exec`); a Local Build switch installs with it. */
108
112
  export declare const runProgram: UpdateDeps['exec'];
109
- /** Starts the background Panel again from the code `sideby` now names; see `UpdateDeps.restartPanel`. */
110
- export declare const restartPanelByName: (env: Env, port: number) => Promise<boolean>;
111
- /** Starts a program detached through the swappable machine; see `UpdateDeps.startDetached`. */
112
- export declare const startDetached: (file: string, args: readonly string[], env: Env) => Promise<boolean>;
113
+ /** The machine in use: the real one, or the parts tests bound. Internal, for after-install.ts and local-build.ts. */
114
+ export declare const updateMachine: () => UpdateDeps;
113
115
  /** The lock every install shares (`update-install.lock`), so a Local Build switch never races an Update. */
114
116
  export declare const takeInstallLock: (paths: Paths) => Promise<(() => Promise<void>) | null>;
115
117
  /** -1, 0 or 1 like a sort comparator; a prerelease sorts before its release. Null when either is not a version. */
@@ -292,6 +294,11 @@ export interface SkillUpdatePlan {
292
294
  export declare function skillUpdatePlan(home: string, target: string): Promise<SkillUpdatePlan | null>;
293
295
  /** Asks the registry now (whatever the switches say: the user asked) and returns what an Update would do. */
294
296
  export declare function planUpdate(paths: Paths, env: Env): Promise<UpdatePlan>;
297
+ /**
298
+ * The plan of `sideby update --skill`: the installed skill toward this version, never the CLI. Asks no registry: what
299
+ * it says of a newer CLI comes from the last Update Check.
300
+ */
301
+ export declare function planSkillUpdate(paths: Paths, env: Env): Promise<UpdatePlan>;
295
302
  /** Updates the installed sideby skill when the plan says it is outdated and sideby may; null when it did nothing. */
296
303
  export declare function applySkillUpdate(plan: SkillUpdatePlan | undefined, env: Env, onOutput?: (text: string) => void): Promise<{
297
304
  ok: boolean;
@@ -323,17 +330,22 @@ export interface UpdateResult {
323
330
  /** The installed sideby skill was updated too (true), or that failed (false); absent when it was not tried. */
324
331
  skillUpdated?: boolean;
325
332
  skillMessage?: string;
333
+ /** With `skillSync: 'background'`: the `sideby update --skill --yes` that updates the skill started on its own. */
334
+ skillSyncStarted?: boolean;
326
335
  }
327
336
  /**
328
- * Runs the Update the plan names, then starts a running background Panel again from the new code and, when the
329
- * desktop app is installed, runs `sideby app install` again from the new code. The caller has
330
- * shown the plan and got a confirmation (or this is an Auto Update). One Update runs at a time on this machine (the
331
- * CLI, a Panel and an Auto Update share the lock). `panelPort` gives the port of the background Panel to restart, or
332
- * null when none runs. A successful Update is recorded as said, so no notice for it follows.
337
+ * Runs the Update the plan names, then what follows an install (after-install.ts): the desktop app and the login item
338
+ * are written again from the new code where installed, the skill follows, and a running background Panel starts again
339
+ * from the new code, last. The caller has shown the plan and got a confirmation (or this is an Auto Update). One
340
+ * Update runs at a time on this machine (the CLI, a Panel and an Auto Update share the lock). `panelPort` gives the
341
+ * port of the background Panel to restart, or null when none runs. A successful Update is recorded as said, so no
342
+ * notice for it follows.
333
343
  */
334
344
  export declare function applyUpdate(paths: Paths, plan: UpdatePlan, env: Env, opts?: {
335
345
  onOutput?: (text: string) => void;
336
346
  panelPort?: () => Promise<number | null>;
347
+ /** `background` (the Panel): the new code updates the skill on its own; see `AfterInstallOptions.skillSync`. */
348
+ skillSync?: 'wait' | 'background';
337
349
  }): Promise<UpdateResult>;
338
350
  /** What keeps an Auto Update from installing `plan` until the user acts (an install it cannot update, a major version). */
339
351
  export declare function lastingBlocker(plan: UpdatePlan): string | null;
@@ -347,4 +359,3 @@ export declare function autoUpdateBlocker(paths: Paths, plan: UpdatePlan): Promi
347
359
  * `update.auto` is on and nothing blocks it. Only one runs at a time; it never throws.
348
360
  */
349
361
  export declare function backgroundCheck(paths: Paths, env: Env, config: UpdateSettings, panelPort: () => Promise<number | null>): Promise<void>;
350
- export {};
@@ -2,13 +2,15 @@
2
2
  // only network request sideby makes on its own: one GET for the `latest` dist-tag, carrying nothing about the user.
3
3
  // Everything it learns goes to one state file shared by the CLI and every Panel.
4
4
  import { spawn } from 'node:child_process';
5
- import { readFileSync } from 'node:fs';
6
- import { access, constants, mkdir, open, readdir, readFile, realpath, rm, stat } from 'node:fs/promises';
5
+ import { access, constants, mkdir, readdir, readFile, realpath, rm } from 'node:fs/promises';
7
6
  import { dirname, join, sep } from 'node:path';
8
7
  import { fileURLToPath } from 'node:url';
8
+ import { afterInstall, runSkillUpdate } from './after-install.js';
9
9
  import { writeFileAtomic } from './fs-safe.js';
10
+ import { processAlive, takeFileLock } from './lock.js';
10
11
  import { installedSkills, SKILL_UPDATE, SKILL_UPDATE_SHOWN, skillOwnerRepo } from './skill-check.js';
11
12
  import { localBuild, packageVersion, parseLocalBuild } from './version.js';
13
+ export { isZombieStat } from './lock.js';
12
14
  export const DEFAULT_REGISTRY = 'https://registry.npmjs.org';
13
15
  export const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
14
16
  export const NOTICE_INTERVAL_MS = 24 * 60 * 60 * 1000;
@@ -18,10 +20,6 @@ export const RETRY_INTERVAL_MS = 60 * 60 * 1000;
18
20
  export const AUTO_RETRY_MS = 24 * 60 * 60 * 1000;
19
21
  const FETCH_TIMEOUT_MS = 5000;
20
22
  export const RELEASE_NOTES = (v) => `https://github.com/Adonis0123/sideby/releases/tag/v${v}`;
21
- /** Whether a Linux `/proc/<pid>/stat` line is of a zombie: the state after the parenthesised command name is `Z`. */
22
- export function isZombieStat(stat) {
23
- return /\)\s+Z\s/.test(stat.slice(stat.lastIndexOf(')')));
24
- }
25
23
  /** Swapped in tests through `bindUpdateDeps`; the real machine otherwise. */
26
24
  /**
27
25
  * Whether `sideby autostart --refresh --json` rewrote the login item: it exits 0 also when nothing changed or the
@@ -58,22 +56,7 @@ const realDeps = {
58
56
  now: () => new Date(),
59
57
  packageDir: ownPackageDir,
60
58
  writable: (dir) => access(dir, constants.W_OK).then(() => true, () => false),
61
- alive(pid) {
62
- try {
63
- process.kill(pid, 0);
64
- }
65
- catch (err) {
66
- return err.code === 'EPERM';
67
- }
68
- // An exited process nobody waited for (its parent went first) still answers signal 0 on Linux: a zombie holds
69
- // no lock and runs no session.
70
- try {
71
- return !isZombieStat(readFileSync(`/proc/${pid}/stat`, 'utf8'));
72
- }
73
- catch {
74
- return true; // no /proc (macOS): signal 0 is the answer
75
- }
76
- },
59
+ alive: processAlive,
77
60
  exec: (file, args, opts) => new Promise((resolve) => {
78
61
  let output = '';
79
62
  const child = spawn(file, args, {
@@ -126,13 +109,16 @@ const realDeps = {
126
109
  child.once('error', () => resolve(false));
127
110
  child.once('close', (code) => resolve(code === 0));
128
111
  }),
129
- autostartInstalled: async (home) => {
112
+ autostartInstalled: async (home, command = 'autostart') => {
130
113
  const { autostartInstalled } = await import('./autostart.js');
131
- return autostartInstalled(home);
114
+ if (command === 'autostart')
115
+ return autostartInstalled(home);
116
+ const { MENUBAR_AGENT } = await import('../menubar/agent.js');
117
+ return autostartInstalled(home, MENUBAR_AGENT);
132
118
  },
133
- refreshAutostart: (env) => new Promise((resolve) => {
119
+ refreshAutostart: (env, command = 'autostart') => new Promise((resolve) => {
134
120
  // By name, like refreshApp: the new code records its own Node and entry; it never creates a login item.
135
- const child = spawn('sideby', ['autostart', '--refresh', '--json'], {
121
+ const child = spawn('sideby', [command, '--refresh', '--json'], {
136
122
  env: env,
137
123
  stdio: ['ignore', 'pipe', 'ignore'],
138
124
  timeout: 60_000,
@@ -158,14 +144,8 @@ export function bindUpdateDeps(deps) {
158
144
  const deps = () => ({ ...realDeps, ...override });
159
145
  /** Runs a program through the swappable machine (tests bind `exec`); a Local Build switch installs with it. */
160
146
  export const runProgram = (file, args, opts) => deps().exec(file, args, opts);
161
- /** Starts the background Panel again from the code `sideby` now names; see `UpdateDeps.restartPanel`. */
162
- export const restartPanelByName = (env, port) => deps()
163
- .restartPanel(env, port)
164
- .catch(() => false);
165
- /** Starts a program detached through the swappable machine; see `UpdateDeps.startDetached`. */
166
- export const startDetached = (file, args, env) => deps()
167
- .startDetached(file, args, env)
168
- .catch(() => false);
147
+ /** The machine in use: the real one, or the parts tests bound. Internal, for after-install.ts and local-build.ts. */
148
+ export const updateMachine = () => deps();
169
149
  /** The lock every install shares (`update-install.lock`), so a Local Build switch never races an Update. */
170
150
  export const takeInstallLock = (paths) => takeLock(paths, 'update-install.lock').catch(() => null);
171
151
  // Build metadata is limited to what semver allows, so a version never carries a terminal escape into the notice.
@@ -376,41 +356,28 @@ export async function refreshUpdateCheck(paths, env) {
376
356
  const LOCK_MAX_MS = 60 * 60 * 1000;
377
357
  /** A lock file another process has just created and not yet written to. */
378
358
  const LOCK_WRITE_GRACE_MS = 60 * 1000;
359
+ /** How often a holder touches its lock, and how long a lock nobody touched counts as held. */
360
+ const LOCK_BEAT_MS = 15 * 1000;
361
+ const LOCK_STALE_MS = 2 * 60 * 1000;
379
362
  /**
380
- * An exclusive lock file in the state directory holding `<pid> <ms since epoch>`. It is held while that pid runs and
381
- * the lock is under an hour old, however long an install takes on a slow mirror; an empty or unreadable lock is held
382
- * for a minute (its owner may still be writing it). Null when held: the second caller fails at once instead of
383
- * waiting. Release removes the file only while it still names this process.
363
+ * An exclusive lock file in the state directory holding `<pid> <ms since epoch>`. It is held while that pid runs, the
364
+ * lock is under an hour old and its holder still touches it (every 15 s), however long an install takes on a slow
365
+ * mirror. A lock not touched for two minutes is free even when its pid runs: a Portal's worker thread that was ended
366
+ * mid-install leaves it behind in a process that lives on. An empty or unreadable lock is held for a minute (its owner
367
+ * may still be writing it). Null when held: the second caller fails at once instead of waiting. Release removes the
368
+ * file only while it still names this process.
384
369
  */
385
370
  async function takeLock(paths, name) {
386
- const file = join(paths.stateDir, name);
387
371
  const d = deps();
388
- const me = `${process.pid} ${d.now().getTime()}`;
389
372
  await mkdir(paths.stateDir, { recursive: true, mode: 0o700 });
390
- for (let attempt = 0; attempt < 2; attempt++) {
391
- try {
392
- const fh = await open(file, 'wx', 0o600);
393
- await fh.writeFile(me);
394
- await fh.close();
395
- return async () => {
396
- if ((await readFile(file, 'utf8').catch(() => '')) === me)
397
- await rm(file, { force: true });
398
- };
399
- }
400
- catch (err) {
401
- if (err.code !== 'EEXIST')
402
- return null;
403
- const text = await readFile(file, 'utf8').catch(() => '');
404
- const m = /^(\d+) (\d+)$/.exec(text);
405
- const held = m
406
- ? d.alive(Number(m[1])) && d.now().getTime() - Number(m[2]) < LOCK_MAX_MS
407
- : d.now().getTime() - ((await stat(file).catch(() => null))?.mtimeMs ?? 0) < LOCK_WRITE_GRACE_MS;
408
- if (held)
409
- return null;
410
- await rm(file, { force: true });
411
- }
412
- }
413
- return null;
373
+ return takeFileLock(join(paths.stateDir, name), {
374
+ alive: d.alive,
375
+ now: () => d.now().getTime(),
376
+ maxMs: LOCK_MAX_MS,
377
+ staleMs: LOCK_STALE_MS,
378
+ beatMs: LOCK_BEAT_MS,
379
+ writeGraceMs: LOCK_WRITE_GRACE_MS,
380
+ }).catch(() => null);
414
381
  }
415
382
  // ---- the notice
416
383
  /**
@@ -743,17 +710,20 @@ export async function planUpdate(paths, env) {
743
710
  const skill = await skillUpdatePlan(paths.home, plan.available ? latest : plan.current).catch(() => null);
744
711
  return skill ? { ...plan, skill } : plan;
745
712
  }
713
+ /**
714
+ * The plan of `sideby update --skill`: the installed skill toward this version, never the CLI. Asks no registry: what
715
+ * it says of a newer CLI comes from the last Update Check.
716
+ */
717
+ export async function planSkillUpdate(paths, env) {
718
+ const current = packageVersion();
719
+ const cache = await readUpdateCache(paths).catch(() => ({}));
720
+ const plan = planFrom(await installMethod(env), current, cache.latest ?? current, env);
721
+ const skill = await skillUpdatePlan(paths.home, current).catch(() => null);
722
+ return skill ? { ...plan, skill } : plan;
723
+ }
746
724
  /** Updates the installed sideby skill when the plan says it is outdated and sideby may; null when it did nothing. */
747
725
  export async function applySkillUpdate(plan, env, onOutput) {
748
- if (!plan?.outdated || !plan.canRun)
749
- return null;
750
- const [file, ...args] = SKILL_UPDATE;
751
- const r = await deps()
752
- .exec(file, args, { env, ...(onOutput ? { onOutput } : {}) })
753
- .catch((e) => ({ code: 1, output: e instanceof Error ? e.message : String(e) }));
754
- return r.code === 0
755
- ? { ok: true, message: 'updated the sideby skill' }
756
- : { ok: false, message: `\`${plan.command}\` failed (exit ${r.code}); run it yourself to see why` };
726
+ return runSkillUpdate(deps(), plan, env, onOutput);
757
727
  }
758
728
  /**
759
729
  * Updates only the sideby skill, for a CLI that is already current (`sideby update`, the Panel, Auto Update). Holds
@@ -777,11 +747,12 @@ export async function applySkillOnly(paths, plan, env, onOutput) {
777
747
  }
778
748
  }
779
749
  /**
780
- * Runs the Update the plan names, then starts a running background Panel again from the new code and, when the
781
- * desktop app is installed, runs `sideby app install` again from the new code. The caller has
782
- * shown the plan and got a confirmation (or this is an Auto Update). One Update runs at a time on this machine (the
783
- * CLI, a Panel and an Auto Update share the lock). `panelPort` gives the port of the background Panel to restart, or
784
- * null when none runs. A successful Update is recorded as said, so no notice for it follows.
750
+ * Runs the Update the plan names, then what follows an install (after-install.ts): the desktop app and the login item
751
+ * are written again from the new code where installed, the skill follows, and a running background Panel starts again
752
+ * from the new code, last. The caller has shown the plan and got a confirmation (or this is an Auto Update). One
753
+ * Update runs at a time on this machine (the CLI, a Panel and an Auto Update share the lock). `panelPort` gives the
754
+ * port of the background Panel to restart, or null when none runs. A successful Update is recorded as said, so no
755
+ * notice for it follows.
785
756
  */
786
757
  export async function applyUpdate(paths, plan, env, opts = {}) {
787
758
  const cmd = updateCommand(plan.method, plan.latest, env);
@@ -800,6 +771,13 @@ export async function applyUpdate(paths, plan, env, opts = {}) {
800
771
  return fail('another sideby update is running; wait for it to finish, then run `sideby update` again', {
801
772
  busy: true,
802
773
  });
774
+ let released = false;
775
+ const free = async () => {
776
+ if (released)
777
+ return;
778
+ released = true;
779
+ await release().catch(() => { });
780
+ };
803
781
  try {
804
782
  const d = deps();
805
783
  const r = await d.exec(cmd.run.file, cmd.run.args, {
@@ -811,30 +789,26 @@ export async function applyUpdate(paths, plan, env, opts = {}) {
811
789
  await updateUpdateCache(paths, {
812
790
  notified: { version: plan.latest, at: d.now().toISOString() },
813
791
  }).catch(() => { });
814
- const port = opts.panelPort ? await opts.panelPort().catch(() => null) : null;
815
- const restarted = port !== null && (await d.restartPanel(env, port).catch(() => false));
816
- // The desktop app records the Node and entry it starts and carries the icon of the version that wrote it, so
817
- // the new code writes it again. Only where one is installed; a failure here never fails the Update.
818
- const installed = await d.appInstalled(paths.home, env).catch(() => false);
819
- const refreshed = installed && (await d.refreshApp(env).catch(() => false));
820
- // The login item records the Node and entry it starts, like the app (ADR-0029); never created here.
821
- const autostart = await d.autostartInstalled(paths.home).catch(() => false);
822
- const refreshedAutostart = autostart ? await d.refreshAutostart(env).catch(() => false) : undefined;
823
792
  // The skill teaches agents this version's commands, so it follows the CLI; a failure there keeps the Update.
824
- const skill = await applySkillUpdate(plan.skill, env, opts.onOutput);
793
+ const after = await afterInstall(d, env, {
794
+ home: paths.home,
795
+ release: free,
796
+ app: true,
797
+ skill: { plan: plan.skill },
798
+ ...(opts.skillSync ? { skillSync: opts.skillSync } : {}),
799
+ ...(opts.panelPort ? { panelPort: opts.panelPort } : {}),
800
+ ...(opts.onOutput ? { onOutput: opts.onOutput } : {}),
801
+ });
825
802
  return {
826
803
  ok: true,
827
804
  code: 0,
828
805
  output: r.output,
829
806
  message: `updated sideby from ${plan.current} to ${plan.latest}`,
830
- restartedPanel: restarted,
831
- refreshedApp: refreshed,
832
- ...(refreshedAutostart !== undefined ? { refreshedAutostart } : {}),
833
- ...(skill ? { skillUpdated: skill.ok, skillMessage: skill.message } : {}),
807
+ ...after,
834
808
  };
835
809
  }
836
810
  finally {
837
- await release().catch(() => { });
811
+ await free();
838
812
  }
839
813
  }
840
814
  /** What keeps an Auto Update from installing `plan` until the user acts (an install it cannot update, a major version). */
@@ -4,7 +4,7 @@
4
4
  // polylines (distance to a segment), ellipses use an analytic distance. Each shape is computed only inside its own
5
5
  // bounding box and composited back to front, fill before outline, as an SVG renderer would.
6
6
  import { deflateSync } from 'node:zlib';
7
- import { BUDDY, highlights, MARK, MARK_COLORS, MARK_VIEWBOX, markSvgBody, } from '../core/brand-mark.js';
7
+ import { buddyShapes, MARK, MARK_COLORS, MARK_VIEWBOX, markSvgBody, } from '../core/brand-mark.js';
8
8
  /** Text stored in every generated file, so `sideby app uninstall` deletes only what it wrote. */
9
9
  export const APP_MARKER = 'sideby-app-install';
10
10
  // The Panel's logo tile (page-styles.ts: .logo 40×40, radius 10); MARK_VIEWBOX maps onto the whole tile square.
@@ -246,23 +246,19 @@ function roundedRectMask(size, s) {
246
246
  }
247
247
  return m;
248
248
  }
249
- /** The shapes of one placed buddy, back to front, each with its colour. */
249
+ /** The shapes of one placed buddy, back to front, each with its colour (core/brand-mark.ts buddyShapes). */
250
250
  function buddyLayers(size, b) {
251
251
  const { k, map } = placement(size, b);
252
- const ink = rgb(MARK_COLORS.ink);
253
- const fills = {
254
- body: b.colors.body,
255
- shade: b.colors.shade,
256
- };
252
+ const { paths, dots, above } = buddyShapes(b);
257
253
  const layers = [];
258
- for (const p of BUDDY.paths) {
259
- const polys = flatten(p.d, map);
260
- if (p.fill !== 'none')
261
- layers.push({ mask: fillMask(size, polys), color: rgb(fills[p.fill]) });
262
- const stroke = p.stroke === 'chevron' ? rgb(b.colors.chevron) : ink;
263
- layers.push({ mask: strokeMask(size, polys, (p.width ?? MARK.placedLine) * k), color: stroke });
264
- }
265
- const dots = [...BUDDY.eyes, ...highlights(b.look)];
254
+ const shape = (s) => {
255
+ const polys = flatten(s.d, map);
256
+ if (s.fill && s.fill !== 'none')
257
+ layers.push({ mask: fillMask(size, polys), color: rgb(s.fill) });
258
+ if (s.stroke !== 'none')
259
+ layers.push({ mask: strokeMask(size, polys, (s.width ?? MARK.placedLine) * k), color: rgb(s.stroke) });
260
+ };
261
+ paths.forEach(shape);
266
262
  for (const e of dots) {
267
263
  const [cx, cy] = map(e.cx, e.cy);
268
264
  layers.push({
@@ -270,6 +266,7 @@ function buddyLayers(size, b) {
270
266
  color: rgb(e.fill === 'ink' ? MARK_COLORS.ink : MARK_COLORS.light),
271
267
  });
272
268
  }
269
+ above.forEach(shape);
273
270
  return layers;
274
271
  }
275
272
  /** RGBA pixels (straight alpha) of the icon at `size`×`size`. */
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `args` without any argument that skips Claude Code's permission checks: the two bypass flags and a
3
+ * `--permission-mode bypassPermissions` (either form). Unless the arguments still pick another permission mode,
4
+ * `--permission-mode auto` comes first: no routine prompts, while auto mode's classifier blocks risky actions. It also
5
+ * outranks a settings file's `permissions.defaultMode`, and a session where auto mode is unavailable starts in Manual.
6
+ * Text after `--` is the Host's own and stays as it is.
7
+ */
8
+ export declare function claudeAiTaskArgs(args: readonly string[]): string[];