sideby 0.42.2 → 0.43.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.
- package/ai-tasks.json +10 -0
- package/dist/build.json +1 -1
- package/dist/src/cli/commands.js +54 -13
- package/dist/src/cli/json-schemas.js +58 -1
- package/dist/src/cli/main.js +11 -4
- package/dist/src/core/ask.d.ts +8 -14
- package/dist/src/core/ask.js +66 -30
- package/dist/src/core/egress.d.ts +5 -0
- package/dist/src/core/egress.js +32 -2
- package/dist/src/core/handoff-run.js +41 -8
- package/dist/src/core/handoff-select.d.ts +5 -0
- package/dist/src/core/handoff-select.js +1 -1
- package/dist/src/core/handoff.d.ts +69 -1
- package/dist/src/core/handoff.js +90 -9
- package/dist/src/core/history-index.d.ts +4 -0
- package/dist/src/core/history-index.js +1 -1
- package/dist/src/core/live-sessions.d.ts +5 -0
- package/dist/src/core/live-sessions.js +12 -1
- package/dist/src/core/network.d.ts +37 -0
- package/dist/src/core/network.js +65 -1
- package/dist/src/core/pick-commands.d.ts +7 -1
- package/dist/src/core/pick-commands.js +15 -3
- package/dist/src/core/pick-records.d.ts +26 -0
- package/dist/src/core/pick-records.js +81 -0
- package/dist/src/families/agy/history.d.ts +2 -0
- package/dist/src/families/agy/history.js +118 -0
- package/dist/src/families/agy/index.js +5 -0
- package/dist/src/families/agy/quota.d.ts +5 -1
- package/dist/src/families/agy/quota.js +111 -10
- package/dist/src/families/history.js +2 -1
- package/dist/src/network/hook.js +4 -4
- package/dist/src/network/page-script.d.ts +40 -0
- package/dist/src/network/page-script.js +270 -0
- package/dist/src/network/page.d.ts +11 -0
- package/dist/src/network/page.js +189 -0
- package/dist/src/network/panel.d.ts +5 -0
- package/dist/src/network/panel.js +7 -0
- package/dist/src/panel/handler.d.ts +21 -1
- package/dist/src/panel/handler.js +174 -37
- package/dist/src/panel/i18n.d.ts +26 -0
- package/dist/src/panel/i18n.js +54 -2
- package/dist/src/panel/page-logic.d.ts +26 -3
- package/dist/src/panel/page-logic.js +95 -12
- package/dist/src/panel/page-script.js +86 -17
- package/dist/src/panel/page-styles.js +1 -0
- package/dist/src/runtime.d.ts +44 -5
- package/dist/src/runtime.js +102 -12
- package/dist/src/types.d.ts +3 -2
- package/package.json +1 -1
- package/schemas/network-diagnose.json +196 -0
- package/schemas/next.json +42 -2
- package/skills/sideby/SKILL.md +2 -1
- package/skills/sideby/references/accounts.md +1 -1
- package/skills/sideby/references/ai-tasks.md +1 -1
- package/skills/sideby/references/handoff.md +4 -2
- package/skills/sideby/references/network.md +6 -1
- package/skills/sideby/references/quota.md +1 -1
- package/skills/sideby/references/sessions.md +1 -1
|
@@ -8,12 +8,18 @@ export declare const DEFAULT_PICK_NAMES: Readonly<Record<string, string>>;
|
|
|
8
8
|
export declare function suggestPickName(family: string, bin: string, familyAliases: readonly string[]): string | null;
|
|
9
9
|
/** What a Pick Command starts this time, or why it starts nothing. */
|
|
10
10
|
export type PickChoice =
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* `pressure`: the used percent of `window`, the window closest to its own Takeover Limit. `running`: the Live
|
|
13
|
+
* Sessions of its login, Pick Records included, when any; `expiring`: its weekly room resets within 24 hours, which
|
|
14
|
+
* is why it goes first (ADR-0083).
|
|
15
|
+
*/
|
|
12
16
|
{
|
|
13
17
|
ref: string;
|
|
14
18
|
reason: 'most-room';
|
|
15
19
|
pressure: number;
|
|
16
20
|
window: string;
|
|
21
|
+
running?: number;
|
|
22
|
+
expiring?: true;
|
|
17
23
|
}
|
|
18
24
|
/**
|
|
19
25
|
* A Last Resort (spec §3.13): every Account is past its Takeover Limits (`limit` for Short Windows, `longLimit` for
|
|
@@ -38,7 +38,14 @@ export function choosePick(plan, mainRef) {
|
|
|
38
38
|
longLimit: plan.tight.longLimit,
|
|
39
39
|
};
|
|
40
40
|
return e.state === 'ready' && e.pressure !== null
|
|
41
|
-
? {
|
|
41
|
+
? {
|
|
42
|
+
ref: plan.pick,
|
|
43
|
+
reason: 'most-room',
|
|
44
|
+
pressure: w.usedPercent,
|
|
45
|
+
window: w.label,
|
|
46
|
+
...(e.liveSessions ? { running: e.liveSessions } : {}),
|
|
47
|
+
...(plan.reason === 'expiring' ? { expiring: true } : {}),
|
|
48
|
+
}
|
|
42
49
|
: { ref: plan.pick, reason: 'others-full' };
|
|
43
50
|
}
|
|
44
51
|
return {
|
|
@@ -55,8 +62,13 @@ export function pickLine(name, choice, family) {
|
|
|
55
62
|
const used = (c) => `${c.window ? `${c.window} ` : ''}${c.pressure}% used`;
|
|
56
63
|
if (choice.reason === 'tight')
|
|
57
64
|
return `${name} → ${choice.ref} (every ${family} account is past its limit, ${choice.limit}% of a 5-hour window or ${choice.longLimit}% of a weekly one; this one has the most left, ${used(choice)})`;
|
|
58
|
-
if (choice.reason === 'most-room')
|
|
59
|
-
|
|
65
|
+
if (choice.reason === 'most-room') {
|
|
66
|
+
if (choice.expiring)
|
|
67
|
+
return `${name} → ${choice.ref} (${used(choice)}; its weekly or monthly quota resets within a day, so it goes first)`;
|
|
68
|
+
return choice.running
|
|
69
|
+
? `${name} → ${choice.ref} (${used(choice)}, ${choice.running} running, the most room per session)`
|
|
70
|
+
: `${name} → ${choice.ref} (${used(choice)}, the most room)`;
|
|
71
|
+
}
|
|
60
72
|
if (choice.reason === 'others-full')
|
|
61
73
|
return `${name} → ${choice.ref} (no quota data for it yet; the accounts with data are full)`;
|
|
62
74
|
return `${name} → ${choice.ref} (no quota data yet; \`sideby quota\` shows why)`;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type PickRecord } from './handoff.ts';
|
|
2
|
+
/** The Pick Records whose time still counts (`pickRecordFresh`); a missing or unreadable file is none. */
|
|
3
|
+
export declare function readPickRecords(stateDir: string, now: Date): Promise<PickRecord[]>;
|
|
4
|
+
/** What a pick that starts something writes: its record, and the records that still count beside it. */
|
|
5
|
+
export interface PickStart {
|
|
6
|
+
ref: string;
|
|
7
|
+
liveAtPick: number;
|
|
8
|
+
/**
|
|
9
|
+
* The records that still count (`activePicks`); the rest, arrived or expired, are dropped from the file, so a record
|
|
10
|
+
* whose Session arrived never counts again when an older Session of that login ends. Left out: all fresh ones stay.
|
|
11
|
+
*/
|
|
12
|
+
keep?: readonly PickRecord[];
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* One pick. `rank` gets the Pick Records and ranks; with `record`, `started` names the Account the caller will start
|
|
16
|
+
* (with its login's load now, `loginLoad`), and its record is written before the lock is let go, then given to
|
|
17
|
+
* `written`. Without `record` nothing is written. A lock that stays busy, or a file that cannot be written, never
|
|
18
|
+
* stops a start: it picks from what it read and writes nothing, so it never puts back an older list over a record
|
|
19
|
+
* another pick wrote meanwhile. The clock is read once the lock is held, so a pick that waited sees its peer's record.
|
|
20
|
+
*/
|
|
21
|
+
export declare function withPickRecords<T>(stateDir: string, clock: () => Date, record: boolean, rank: (picks: readonly PickRecord[], now: Date) => Promise<T>, started: (result: T, picks: readonly PickRecord[], now: Date) => PickStart | null, written?: (rec: PickRecord) => void): Promise<T>;
|
|
22
|
+
/**
|
|
23
|
+
* Takes back a record whose start did not happen (the user stayed, the terminal did not open), so it does not count
|
|
24
|
+
* for two minutes. Without the lock it leaves the file alone: the record then expires by itself.
|
|
25
|
+
*/
|
|
26
|
+
export declare function dropPickRecord(stateDir: string, rec: PickRecord): Promise<void>;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Pick Records (spec §3.13 "分摊选号", ADR-0083): a short-lived note in sideby's state directory that a pick just
|
|
2
|
+
// started an Account, so picks made at the same moment do not all land on one Account. A pick that starts something
|
|
3
|
+
// holds one lock across counting Live Sessions, ranking and writing its record; a preview only reads.
|
|
4
|
+
import { mkdir, readFile } from 'node:fs/promises';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { writeFileAtomic } from './fs-safe.js';
|
|
7
|
+
import { pickRecordFresh } from './handoff.js';
|
|
8
|
+
import { takeFileLock } from './lock.js';
|
|
9
|
+
const DIR = 'picks';
|
|
10
|
+
const FILE = 'records.json';
|
|
11
|
+
/** Counting Live Sessions takes about half a second; a holder that stopped frees the lock within seconds. */
|
|
12
|
+
const LOCK = { staleMs: 10_000, beatMs: 2_000, maxMs: 60_000 };
|
|
13
|
+
/** How long a pick waits for another one to finish before it goes on without the lock. */
|
|
14
|
+
const WAIT_MS = 5_000;
|
|
15
|
+
const isRecord = (r) => typeof r === 'object' &&
|
|
16
|
+
r !== null &&
|
|
17
|
+
typeof r.ref === 'string' &&
|
|
18
|
+
typeof r.at === 'string' &&
|
|
19
|
+
Number.isFinite(r.liveAtPick);
|
|
20
|
+
/** The Pick Records whose time still counts (`pickRecordFresh`); a missing or unreadable file is none. */
|
|
21
|
+
export async function readPickRecords(stateDir, now) {
|
|
22
|
+
let list;
|
|
23
|
+
try {
|
|
24
|
+
list = JSON.parse(await readFile(join(stateDir, DIR, FILE), 'utf8'));
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
if (!Array.isArray(list))
|
|
30
|
+
return [];
|
|
31
|
+
return list.filter(isRecord).filter((r) => pickRecordFresh(r.at, now));
|
|
32
|
+
}
|
|
33
|
+
async function takePickLock(stateDir) {
|
|
34
|
+
const dir = join(stateDir, DIR);
|
|
35
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
36
|
+
return takeFileLock(join(dir, 'pick.lock'), { ...LOCK, wait: { timeoutMs: WAIT_MS, pollMs: 50 } });
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* One pick. `rank` gets the Pick Records and ranks; with `record`, `started` names the Account the caller will start
|
|
40
|
+
* (with its login's load now, `loginLoad`), and its record is written before the lock is let go, then given to
|
|
41
|
+
* `written`. Without `record` nothing is written. A lock that stays busy, or a file that cannot be written, never
|
|
42
|
+
* stops a start: it picks from what it read and writes nothing, so it never puts back an older list over a record
|
|
43
|
+
* another pick wrote meanwhile. The clock is read once the lock is held, so a pick that waited sees its peer's record.
|
|
44
|
+
*/
|
|
45
|
+
export async function withPickRecords(stateDir, clock, record, rank, started, written) {
|
|
46
|
+
const release = record ? await takePickLock(stateDir).catch(() => null) : null;
|
|
47
|
+
try {
|
|
48
|
+
const now = clock();
|
|
49
|
+
const picks = await readPickRecords(stateDir, now);
|
|
50
|
+
const result = await rank(picks, now);
|
|
51
|
+
const start = release ? started(result, picks, now) : null;
|
|
52
|
+
if (start) {
|
|
53
|
+
const rec = { ref: start.ref, at: now.toISOString(), liveAtPick: start.liveAtPick };
|
|
54
|
+
const next = [...(start.keep ?? picks), rec];
|
|
55
|
+
if (await writeFileAtomic(join(stateDir, DIR, FILE), `${JSON.stringify(next)}\n`).catch(() => false))
|
|
56
|
+
written?.(rec);
|
|
57
|
+
}
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
await release?.();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Takes back a record whose start did not happen (the user stayed, the terminal did not open), so it does not count
|
|
66
|
+
* for two minutes. Without the lock it leaves the file alone: the record then expires by itself.
|
|
67
|
+
*/
|
|
68
|
+
export async function dropPickRecord(stateDir, rec) {
|
|
69
|
+
const release = await takePickLock(stateDir).catch(() => null);
|
|
70
|
+
if (!release)
|
|
71
|
+
return;
|
|
72
|
+
try {
|
|
73
|
+
const picks = await readPickRecords(stateDir, new Date());
|
|
74
|
+
const next = picks.filter((r) => !(r.ref === rec.ref && r.at === rec.at));
|
|
75
|
+
if (next.length !== picks.length)
|
|
76
|
+
await writeFileAtomic(join(stateDir, DIR, FILE), `${JSON.stringify(next)}\n`).catch(() => false);
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
await release();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Antigravity CLI's Session History (spec §3.33, ADR-0082): agy lists its conversations in
|
|
2
|
+
// `conversation_summaries.db` (SQLite, table `conversation_summaries`) in the Account folder, one row per conversation
|
|
3
|
+
// with its title, step count, last change and workspace folders (tried with agy 1.5.14 on 2026-11-23). The
|
|
4
|
+
// conversations themselves are binary records in `conversations/<id>.db`, which sideby never opens: a Session is listed
|
|
5
|
+
// and found by its title and folder, and `history show` has no messages to show. Subagent conversations
|
|
6
|
+
// (`parent_conversation_id` set or `nesting_depth` above 0) and rows without a title are left out.
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { stat } from 'node:fs/promises';
|
|
9
|
+
import { basename, join } from 'node:path';
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
11
|
+
import { loadSqlite } from '../../core/history-index.js';
|
|
12
|
+
import { isoTime, titleFromText } from '../shared/history-text.js';
|
|
13
|
+
const DB = 'conversation_summaries.db';
|
|
14
|
+
const COLUMNS = 'conversation_id, title, step_count, last_modified_time, workspace_uris';
|
|
15
|
+
const TOP_LEVEL = "parent_conversation_id = '' AND nesting_depth = 0 AND title <> ''";
|
|
16
|
+
/** The rows `list` read last, by record path, so `parse` does not open the database once per Session. */
|
|
17
|
+
const lastRows = new Map();
|
|
18
|
+
/** Rows of agy's summary database, opened read-only; empty when the file is not there. */
|
|
19
|
+
async function readRows(dir, where, args = []) {
|
|
20
|
+
const file = join(dir, DB);
|
|
21
|
+
try {
|
|
22
|
+
if (!(await stat(file)).isFile())
|
|
23
|
+
return [];
|
|
24
|
+
}
|
|
25
|
+
catch (err) {
|
|
26
|
+
if (err.code === 'ENOENT')
|
|
27
|
+
return [];
|
|
28
|
+
throw err;
|
|
29
|
+
}
|
|
30
|
+
const sqlite = await loadSqlite();
|
|
31
|
+
if (!sqlite)
|
|
32
|
+
return [];
|
|
33
|
+
// A read-only open of a WAL database creates its `-wal` and `-shm` files when they are missing, which would write
|
|
34
|
+
// into agy's folder. While agy has them (it is running), they are read as agy left them, to see its newest rows;
|
|
35
|
+
// otherwise the file is opened as `immutable`, which creates nothing (tried with Node 22.23 on 2026-11-23).
|
|
36
|
+
const live = (await Promise.all(['-wal', '-shm'].map((x) => stat(file + x).then(() => true, () => false)))).every(Boolean);
|
|
37
|
+
let target = file;
|
|
38
|
+
if (!live) {
|
|
39
|
+
target = pathToFileURL(file);
|
|
40
|
+
target.searchParams.set('immutable', '1');
|
|
41
|
+
}
|
|
42
|
+
const db = new sqlite.DatabaseSync(target, { readOnly: true });
|
|
43
|
+
try {
|
|
44
|
+
return db
|
|
45
|
+
.prepare(`SELECT ${COLUMNS} FROM conversation_summaries WHERE ${where}`)
|
|
46
|
+
.all(...args);
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
db.close();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** The key a Session is indexed by: its record file, which is never opened. */
|
|
53
|
+
const recordPath = (dir, id) => join(dir, 'conversations', `${id}.db`);
|
|
54
|
+
/** The first local folder of the conversation's workspaces. */
|
|
55
|
+
function firstFolder(uris) {
|
|
56
|
+
try {
|
|
57
|
+
const list = JSON.parse(uris);
|
|
58
|
+
if (!Array.isArray(list))
|
|
59
|
+
return undefined;
|
|
60
|
+
for (const u of list)
|
|
61
|
+
if (typeof u === 'string' && u.startsWith('file://'))
|
|
62
|
+
return fileURLToPath(u);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
const plainId = (id) => typeof id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(id);
|
|
70
|
+
export const agyHistory = {
|
|
71
|
+
family: 'agy',
|
|
72
|
+
async list(account) {
|
|
73
|
+
const out = [];
|
|
74
|
+
for (const r of await readRows(account.dir, `${TOP_LEVEL} ORDER BY last_modified_time DESC`)) {
|
|
75
|
+
if (!plainId(r.conversation_id))
|
|
76
|
+
continue;
|
|
77
|
+
const path = recordPath(account.dir, r.conversation_id);
|
|
78
|
+
const at = Date.parse(r.last_modified_time);
|
|
79
|
+
lastRows.set(path, r);
|
|
80
|
+
out.push({
|
|
81
|
+
path,
|
|
82
|
+
sig: createHash('sha256')
|
|
83
|
+
.update(JSON.stringify([r.title, r.step_count, r.last_modified_time, r.workspace_uris]))
|
|
84
|
+
.digest('hex')
|
|
85
|
+
.slice(0, 32),
|
|
86
|
+
mtimeMs: Number.isFinite(at) ? at : 0,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
},
|
|
91
|
+
async parse(file, account) {
|
|
92
|
+
const id = basename(file.path, '.db');
|
|
93
|
+
let row = lastRows.get(file.path);
|
|
94
|
+
if (!row)
|
|
95
|
+
[row] = await readRows(account.dir, `conversation_id = ? AND ${TOP_LEVEL}`, [id]);
|
|
96
|
+
if (!row || row.conversation_id !== id)
|
|
97
|
+
return undefined;
|
|
98
|
+
const updatedAt = isoTime(row.last_modified_time);
|
|
99
|
+
const s = {
|
|
100
|
+
sessionId: id,
|
|
101
|
+
title: titleFromText(row.title),
|
|
102
|
+
titleFrom: 'host',
|
|
103
|
+
messages: 0,
|
|
104
|
+
script: false,
|
|
105
|
+
prompts: [],
|
|
106
|
+
replies: [],
|
|
107
|
+
};
|
|
108
|
+
const cwd = firstFolder(row.workspace_uris);
|
|
109
|
+
if (cwd)
|
|
110
|
+
s.cwd = cwd;
|
|
111
|
+
if (updatedAt)
|
|
112
|
+
s.updatedAt = updatedAt;
|
|
113
|
+
return s;
|
|
114
|
+
},
|
|
115
|
+
// The conversation is a binary record sideby does not read.
|
|
116
|
+
async *messages() { },
|
|
117
|
+
async *toolText() { },
|
|
118
|
+
};
|
|
@@ -46,6 +46,11 @@ export const agyFamily = {
|
|
|
46
46
|
async loginState() {
|
|
47
47
|
return 'unknown';
|
|
48
48
|
},
|
|
49
|
+
// agy keeps no record sideby reads for this: only a quota check that met agy's sign-in page marks the login
|
|
50
|
+
// expired (`loginExpired`, ADR-0082), and a later good answer clears it.
|
|
51
|
+
async readLoginEvents() {
|
|
52
|
+
return {};
|
|
53
|
+
},
|
|
49
54
|
fetchQuota: agyQuotaFetch,
|
|
50
55
|
};
|
|
51
56
|
export const agyPlugin = {
|
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import type { Account, QuotaFetch, QuotaFetchContext, QuotaResult } from '../../types.ts';
|
|
2
2
|
export declare const AGY_QUOTA_ARGS: readonly ['-p', '/usage', '--output-format', 'json'];
|
|
3
|
+
/** agy's own limit, under sideby's `FETCH_TIMEOUT_MS`, so agy is stopped here and has time to exit. */
|
|
4
|
+
export declare const AGY_QUOTA_TIMEOUT_MS = 15000;
|
|
3
5
|
/**
|
|
4
6
|
* The Quota in agy's JSON answer: one window per bucket, named after its model group, since each limit covers only
|
|
5
7
|
* that group's models. Only group names, windows, percentages and reset times are kept.
|
|
6
8
|
*/
|
|
7
9
|
export declare function agyQuota(answer: unknown, observedAt: string): QuotaResult | null;
|
|
8
|
-
export declare function fetchAgyQuota(account: Account, ctx: QuotaFetchContext
|
|
10
|
+
export declare function fetchAgyQuota(account: Account, ctx: QuotaFetchContext, opts?: {
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
}): Promise<QuotaResult>;
|
|
9
13
|
export declare const agyQuotaFetch: QuotaFetch;
|
|
@@ -1,11 +1,38 @@
|
|
|
1
1
|
// Asks Antigravity CLI for the Main Account's Quota (spec §3.26, ADR-0048): `agy -p /usage --output-format json` runs
|
|
2
2
|
// the `/usage` command with agy's own sign-in and starts no model turn (`num_turns` 0, every token count 0; tried with
|
|
3
3
|
// agy 1.4.4 on 2026-10-21). sideby never reads the sign-in and sends no request of its own.
|
|
4
|
+
//
|
|
5
|
+
// A background check must never open a browser (ADR-0082). When agy cannot refresh its sign-in, `-p` prints a sign-in
|
|
6
|
+
// link, runs `open <link>` (`xdg-open` on Linux), looked up on PATH, and waits 60 s for the sign-in (agy 1.5.14,
|
|
7
|
+
// 2026-11-23). agy has no BROWSER or NO_BROWSER variable; it skips the browser in an SSH session, but then gives no
|
|
8
|
+
// sign that it waits. So the check puts sideby's own `open` first on agy's PATH: it opens nothing and leaves a mark,
|
|
9
|
+
// and sideby stops agy at once and says to sign in again.
|
|
4
10
|
import { spawn } from 'node:child_process';
|
|
5
|
-
import {
|
|
11
|
+
import { randomBytes } from 'node:crypto';
|
|
12
|
+
import { existsSync } from 'node:fs';
|
|
13
|
+
import { readFile, rm, stat } from 'node:fs/promises';
|
|
14
|
+
import { delimiter, join } from 'node:path';
|
|
15
|
+
import { ownedFolder, writeFileAtomic } from '../../core/fs-safe.js';
|
|
6
16
|
export const AGY_QUOTA_ARGS = ['-p', '/usage', '--output-format', 'json'];
|
|
7
17
|
/** agy answers in about 6 s; anything far larger than its answer is not one. */
|
|
8
18
|
const MAX_OUTPUT = 256 * 1024;
|
|
19
|
+
/** agy's own limit, under sideby's `FETCH_TIMEOUT_MS`, so agy is stopped here and has time to exit. */
|
|
20
|
+
export const AGY_QUOTA_TIMEOUT_MS = 15_000;
|
|
21
|
+
/** After SIGTERM, how long agy gets to exit before SIGKILL. */
|
|
22
|
+
const KILL_AFTER_MS = 2_000;
|
|
23
|
+
/** How often the check looks for the sign-in mark. */
|
|
24
|
+
const MARK_POLL_MS = 200;
|
|
25
|
+
/** Names agy may run to open its sign-in page. */
|
|
26
|
+
// Linux and WSL builds of agy may also try sensible-browser.
|
|
27
|
+
const OPENERS = ['open', 'xdg-open', 'sensible-browser'];
|
|
28
|
+
/** Where sideby's `open` leaves its mark; set only for the quota check. */
|
|
29
|
+
const MARK_VAR = 'SIDEBY_AGY_SIGN_IN_MARK';
|
|
30
|
+
const OPENER = `#!/bin/sh
|
|
31
|
+
# sideby's Antigravity CLI quota check (ADR-0082): agy asked to open its sign-in page. Open nothing, keep nothing of
|
|
32
|
+
# the address, only leave the mark sideby looks for.
|
|
33
|
+
[ -n "$${MARK_VAR}" ] && : > "$${MARK_VAR}"
|
|
34
|
+
exit 0
|
|
35
|
+
`;
|
|
9
36
|
const failed = (detail) => ({ status: 'unavailable', reason: 'fetch-failed', detail });
|
|
10
37
|
const WINDOWS = {
|
|
11
38
|
'5h': { label: '5h', minutes: 300 },
|
|
@@ -57,19 +84,74 @@ function errorDetail(account, answer) {
|
|
|
57
84
|
return `Antigravity CLI is not signed in; run \`sideby login ${account.ref}\` and sign in with Google`;
|
|
58
85
|
return 'Antigravity CLI could not report the quota; sideby asks again later, or start agy once';
|
|
59
86
|
}
|
|
60
|
-
|
|
87
|
+
const needsSignIn = (account) => ({
|
|
88
|
+
status: 'unavailable',
|
|
89
|
+
reason: 'fetch-failed',
|
|
90
|
+
detail: `Antigravity CLI needs a new sign-in; run \`sideby login ${account.ref}\` and sign in with Google`,
|
|
91
|
+
loginExpired: true,
|
|
92
|
+
});
|
|
93
|
+
/** sideby's folder for the check, with its `open` in `bin`; null when it is not safe to use. */
|
|
94
|
+
async function checkFolder(stateDir) {
|
|
95
|
+
try {
|
|
96
|
+
const dir = await ownedFolder(stateDir, ['quota', 'agy-run'], { create: true });
|
|
97
|
+
const bin = await ownedFolder(stateDir, ['quota', 'agy-run', 'bin'], { create: true });
|
|
98
|
+
if (!dir || !bin)
|
|
99
|
+
return null;
|
|
100
|
+
for (const name of OPENERS) {
|
|
101
|
+
const p = join(bin, name);
|
|
102
|
+
// agy looks openers up on PATH and skips files that are not executable, so the mode matters too.
|
|
103
|
+
const same = (await readFile(p, 'utf8').catch(() => null)) === OPENER;
|
|
104
|
+
const mode = (await stat(p).catch(() => null))?.mode;
|
|
105
|
+
if (!same || mode === undefined || (mode & 0o777) !== 0o700)
|
|
106
|
+
await writeFileAtomic(p, OPENER, 0o700);
|
|
107
|
+
}
|
|
108
|
+
return { dir, bin };
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export async function fetchAgyQuota(account, ctx, opts = {}) {
|
|
61
115
|
if (ctx.signal.aborted)
|
|
62
116
|
return failed('the quota check was stopped');
|
|
117
|
+
const folder = await checkFolder(ctx.stateDir);
|
|
118
|
+
// Without sideby's `open` first on PATH, agy could open a browser: it is not asked.
|
|
119
|
+
if (!folder)
|
|
120
|
+
return failed(`sideby's folder ${join(ctx.stateDir, 'quota')} is not safe to use; check its owner and mode`);
|
|
121
|
+
if (ctx.signal.aborted)
|
|
122
|
+
return failed('the quota check was stopped');
|
|
123
|
+
const mark = join(folder.dir, `sign-in-${randomBytes(8).toString('hex')}`);
|
|
63
124
|
const child = spawn('agy', [...AGY_QUOTA_ARGS], {
|
|
64
|
-
cwd:
|
|
65
|
-
env:
|
|
125
|
+
cwd: folder.dir,
|
|
126
|
+
env: {
|
|
127
|
+
...ctx.hostEnv,
|
|
128
|
+
PATH: [folder.bin, ctx.hostEnv.PATH].filter(Boolean).join(delimiter),
|
|
129
|
+
[MARK_VAR]: mark,
|
|
130
|
+
},
|
|
66
131
|
// stderr holds a sign-in link when signed out: never read.
|
|
67
132
|
stdio: ['ignore', 'pipe', 'ignore'],
|
|
68
133
|
});
|
|
134
|
+
const alive = () => child.exitCode === null && child.signalCode === null;
|
|
135
|
+
let killTimer;
|
|
136
|
+
// SIGTERM lets agy print its answer and exit (it does within a second); SIGKILL if it does not.
|
|
69
137
|
const stop = () => {
|
|
70
|
-
if (
|
|
71
|
-
|
|
138
|
+
if (!alive())
|
|
139
|
+
return;
|
|
140
|
+
child.kill('SIGTERM');
|
|
141
|
+
killTimer ??= setTimeout(() => alive() && child.kill('SIGKILL'), KILL_AFTER_MS);
|
|
72
142
|
};
|
|
143
|
+
let signIn = false;
|
|
144
|
+
let timedOut = false;
|
|
145
|
+
const poll = setInterval(() => {
|
|
146
|
+
if (!signIn && existsSync(mark)) {
|
|
147
|
+
signIn = true;
|
|
148
|
+
stop();
|
|
149
|
+
}
|
|
150
|
+
}, MARK_POLL_MS);
|
|
151
|
+
const deadline = setTimeout(() => {
|
|
152
|
+
timedOut = true;
|
|
153
|
+
stop();
|
|
154
|
+
}, opts.timeoutMs ?? AGY_QUOTA_TIMEOUT_MS);
|
|
73
155
|
ctx.signal.addEventListener('abort', stop, { once: true });
|
|
74
156
|
try {
|
|
75
157
|
return await new Promise((resolve) => {
|
|
@@ -84,7 +166,11 @@ export async function fetchAgyQuota(account, ctx) {
|
|
|
84
166
|
child.on('error', (err) => resolve(failed(err.code === 'ENOENT'
|
|
85
167
|
? 'Antigravity CLI is not installed or not on PATH; install it, then refresh'
|
|
86
168
|
: `could not start Antigravity CLI (${err.code ?? 'error'})`)));
|
|
87
|
-
|
|
169
|
+
const done = () => {
|
|
170
|
+
// A process agy started may still hold the output open; let go of it so sideby itself can exit.
|
|
171
|
+
child.stdout.destroy();
|
|
172
|
+
if (signIn || existsSync(mark))
|
|
173
|
+
return resolve(needsSignIn(account));
|
|
88
174
|
if (ctx.signal.aborted)
|
|
89
175
|
return resolve(failed('the quota check was stopped'));
|
|
90
176
|
let answer;
|
|
@@ -92,15 +178,30 @@ export async function fetchAgyQuota(account, ctx) {
|
|
|
92
178
|
answer = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
93
179
|
}
|
|
94
180
|
catch {
|
|
95
|
-
|
|
181
|
+
answer = undefined;
|
|
96
182
|
}
|
|
97
|
-
|
|
98
|
-
|
|
183
|
+
const quota = answer === undefined ? null : agyQuota(answer, ctx.now.toISOString());
|
|
184
|
+
if (quota)
|
|
185
|
+
return resolve(quota);
|
|
186
|
+
if (timedOut)
|
|
187
|
+
return resolve(failed(`Antigravity CLI gave no answer within ${Math.round((opts.timeoutMs ?? AGY_QUOTA_TIMEOUT_MS) / 1000)} seconds; sideby asks again later`));
|
|
188
|
+
if (answer === undefined)
|
|
189
|
+
return resolve(failed('Antigravity CLI exited without answering; sideby asks again later'));
|
|
190
|
+
resolve(failed(errorDetail(account, answer)));
|
|
191
|
+
};
|
|
192
|
+
child.on('close', done);
|
|
193
|
+
// A process agy started may keep its output open after agy ended: answer anyway.
|
|
194
|
+
child.on('exit', () => setTimeout(done, 1_000).unref());
|
|
99
195
|
});
|
|
100
196
|
}
|
|
101
197
|
finally {
|
|
198
|
+
clearInterval(poll);
|
|
199
|
+
clearTimeout(deadline);
|
|
102
200
|
ctx.signal.removeEventListener('abort', stop);
|
|
103
201
|
stop();
|
|
202
|
+
if (killTimer && !alive())
|
|
203
|
+
clearTimeout(killTimer);
|
|
204
|
+
await rm(mark, { force: true }).catch(() => { });
|
|
104
205
|
}
|
|
105
206
|
}
|
|
106
207
|
export const agyQuotaFetch = {
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { readdir } from 'node:fs/promises';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
|
+
import { agyHistory } from './agy/history.js';
|
|
3
4
|
import { claudeHistory } from './claude/history.js';
|
|
4
5
|
import { codexHistory } from './codex/history.js';
|
|
5
6
|
import { grokHistory } from './grok/history.js';
|
|
6
7
|
import { piHistory } from './pi/history.js';
|
|
7
8
|
import { cutText, SESSION_TEXT_MAX, TITLE_MAX, titleFromText } from './shared/history-text.js';
|
|
8
|
-
const READERS = new Map([claudeHistory, codexHistory, grokHistory, piHistory].map((r) => [r.family, r]));
|
|
9
|
+
const READERS = new Map([claudeHistory, codexHistory, grokHistory, piHistory, agyHistory].map((r) => [r.family, r]));
|
|
9
10
|
const PLUGIN_READERS = new WeakMap();
|
|
10
11
|
async function* nothing() { }
|
|
11
12
|
const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === 'string');
|
package/dist/src/network/hook.js
CHANGED
|
@@ -9,7 +9,7 @@ import { spawn } from 'node:child_process';
|
|
|
9
9
|
import { lstat, readdir, unlink } from 'node:fs/promises';
|
|
10
10
|
import { join } from 'node:path';
|
|
11
11
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
12
|
-
import { blockMessage, inCi, judge, NETWORK_ENV, prefersChinese, readNetworkConfig, refresh, verdict, } from '../core/egress.js';
|
|
12
|
+
import { blockMessage, inCi, judge, NETWORK_ENV, prefersChinese, readNetworkConfig, refresh, routeLabel, verdict, } from '../core/egress.js';
|
|
13
13
|
import { ownedFolder, readSmallFile, sha256, writeFileAtomic } from '../core/fs-safe.js';
|
|
14
14
|
import { resolvePaths } from '../core/paths.js';
|
|
15
15
|
import { HELD_CLOSE, HELD_OPEN, hookWakeUp, hostMade } from '../core/prompt-origin.js';
|
|
@@ -249,14 +249,14 @@ export async function runNetworkHook(argv, env, err, deps = {}) {
|
|
|
249
249
|
return 0;
|
|
250
250
|
}
|
|
251
251
|
await decided('blocked');
|
|
252
|
-
err.write(`${blockMessage(v, allow, { ref: env.SIDEBY_LABEL || env.SIDEBY_ACCOUNT, at: moment, zh: prefersChinese(env) })}\n`);
|
|
252
|
+
err.write(`${blockMessage(v, allow, { ref: env.SIDEBY_LABEL || env.SIDEBY_ACCOUNT, at: moment, zh: prefersChinese(env), proxy: routeLabel(url, env) })}\n`);
|
|
253
253
|
return 2;
|
|
254
254
|
}
|
|
255
255
|
catch {
|
|
256
256
|
await decided('blocked');
|
|
257
257
|
err.write(`${prefersChinese(env)
|
|
258
|
-
?
|
|
259
|
-
:
|
|
258
|
+
? `已拦截:sideby 的网络检查出错,没能确认网络出口。本次检查使用${routeLabel(url, env) === 'direct' ? '直连(direct)' : `代理 \`${routeLabel(url, env)}\``}。重新发送试试;旧会话可能要重开才能继承新的代理环境;一直出错就运行 \`sideby network diagnose\`。`
|
|
259
|
+
: `Blocked: sideby's network check failed and could not tell this network's exit. This check used ${routeLabel(url, env) === 'direct' ? 'a direct connection (direct)' : `proxy \`${routeLabel(url, env)}\``}. Try again; an older session may need restarting to inherit a changed proxy environment; if it keeps failing, run \`sideby network diagnose\`.`}\n`);
|
|
260
260
|
return 2;
|
|
261
261
|
}
|
|
262
262
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { NetworkDiagnosis } from '../core/network.ts';
|
|
2
|
+
import { networkDiagnoseTaskFacts } from '../panel/page-logic.ts';
|
|
3
|
+
type Api = (path: string, body: Record<string, unknown>) => Promise<unknown>;
|
|
4
|
+
type AskResult = {
|
|
5
|
+
opened: boolean;
|
|
6
|
+
command?: string | null;
|
|
7
|
+
reason?: string;
|
|
8
|
+
detail?: string;
|
|
9
|
+
};
|
|
10
|
+
type AskState = {
|
|
11
|
+
body: Record<string, unknown>;
|
|
12
|
+
prompt: string;
|
|
13
|
+
loading: boolean;
|
|
14
|
+
busy: boolean;
|
|
15
|
+
promptChanged: boolean;
|
|
16
|
+
error: string | null;
|
|
17
|
+
result: AskResult | null;
|
|
18
|
+
};
|
|
19
|
+
/** One controller per document; a null Ask is a closed dialog and invalidates every pending continuation. */
|
|
20
|
+
export declare function networkPageController(opts: {
|
|
21
|
+
api: Api;
|
|
22
|
+
facts?: typeof networkDiagnoseTaskFacts;
|
|
23
|
+
version: string;
|
|
24
|
+
lang: string;
|
|
25
|
+
onChange?: () => void;
|
|
26
|
+
}): {
|
|
27
|
+
state: {
|
|
28
|
+
diagnosis: NetworkDiagnosis | null;
|
|
29
|
+
loading: boolean;
|
|
30
|
+
error: string | null;
|
|
31
|
+
ask: AskState | null;
|
|
32
|
+
};
|
|
33
|
+
start(): Promise<void>;
|
|
34
|
+
diagnose(): Promise<void>;
|
|
35
|
+
openAsk(): Promise<void>;
|
|
36
|
+
closeAsk(): void;
|
|
37
|
+
confirmAsk(): Promise<void>;
|
|
38
|
+
};
|
|
39
|
+
export declare const NETWORK_PAGE_SCRIPT: string;
|
|
40
|
+
export {};
|