agentschat-mcp 0.36.25 → 0.36.27
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/CHANGELOG.md +7 -0
- package/README.md +10 -10
- package/codex/README.md +4 -4
- package/codex/app-server.ts +101 -22
- package/codex/bots-config.ts +32 -11
- package/codex/bridge.ts +127 -28
- package/codex/config.ts +137 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +77 -12
- package/codex/loop-grants.ts +49 -11
- package/codex/manager.ts +108 -27
- package/codex/owner.ts +106 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +51 -11
- package/codex/thread-history.ts +87 -30
- package/codex/transport.ts +135 -22
- package/connector/README.md +1 -1
- package/connector/auth.ts +57 -5
- package/connector/backfill.ts +92 -10
- package/connector/descriptor.ts +27 -1
- package/connector/identities.ts +82 -14
- package/connector/ingest.ts +11 -2
- package/connector/normalize.ts +32 -12
- package/connector/run.ts +314 -67
- package/connector/server.ts +95 -26
- package/cordis.patch.yml +4 -2
- package/dist/codex-bots.js +437 -75
- package/dist/codex-bridge.js +2111 -582
- package/dist/connector.js +1300 -493
- package/dist/dsh.js +1789 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +4410 -919
- package/dsh/README.md +1 -1
- package/dsh/client.js +7 -5
- package/dsh/identity-ui/client.js +7 -5
- package/dsh/identity-ui/index.js +43 -8
- package/dsh/inbound-bridge/index.js +677 -154
- package/dsh/src/cli.ts +430 -91
- package/dsh/src/patch.ts +295 -15
- package/dsh/tests/dsh-hardening-127.test.ts +207 -0
- package/dsh/tests/dsh.test.ts +1174 -3
- package/muse/scripts/ensure-muse-wakes.mjs +5 -3
- package/muse/scripts/muse-wake-receiver.mjs +4 -1
- package/muse/src/bridge.ts +54 -13
- package/muse/src/cli.ts +226 -41
- package/muse/src/client.ts +249 -34
- package/muse/src/config.ts +128 -12
- package/muse/src/policy.ts +28 -8
- package/muse/src/types.ts +1 -0
- package/muse/src/typing.ts +18 -1
- package/muse/src/wake.ts +237 -35
- package/muse/tests/bridge.test.mjs +131 -0
- package/muse/tests/client.test.mjs +327 -0
- package/muse/tests/config.test.mjs +78 -1
- package/muse/tests/hardening.test.mjs +199 -0
- package/muse/tests/hardening126.test.mjs +292 -0
- package/muse/tests/policy.test.mjs +83 -1
- package/muse/tests/wake.test.mjs +134 -6
- package/package.json +3 -3
- package/scripts/ensure-grok-wakes.mjs +93 -8
- package/scripts/example-url-wake-receiver.mjs +254 -61
- package/scripts/grok-bind-register.sh +38 -8
- package/skills/onboarding.md +15 -15
- package/src/argcheck.ts +113 -33
- package/src/cli.mjs +100 -16
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +182 -33
- package/src/heartbeat.ts +39 -11
- package/src/identity-guard.ts +93 -20
- package/src/identity.ts +67 -11
- package/src/mentions.ts +26 -5
- package/src/onboarding-status.ts +134 -11
- package/src/profile-selection.ts +299 -18
- package/src/profile-store.ts +248 -30
- package/src/read-cursor.ts +280 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +286 -94
- package/src/session-bind.ts +777 -134
- package/src/session-route.ts +183 -12
- package/src/team-lead-skill.ts +3 -0
- package/src/timestamps.ts +56 -23
- package/src/tool-annotations.ts +10 -1
- package/src/wake.ts +510 -91
package/codex/inbox-sync.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { chmodSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
2
3
|
import { join } from "node:path";
|
|
4
|
+
import { assertDirectoryAncestors, atomicReplaceRegularFile } from "./config.ts";
|
|
3
5
|
import { normalizeTimestampForCursor } from "../src/timestamps.ts";
|
|
4
6
|
|
|
5
7
|
interface Snapshot {
|
|
@@ -10,8 +12,32 @@ interface Snapshot {
|
|
|
10
12
|
last_error?: string;
|
|
11
13
|
}
|
|
12
14
|
function timestamp(value: unknown): string {
|
|
13
|
-
if (typeof value !== "string" || !Number.isFinite(Date.parse(value))) throw new Error("Invalid history timestamp");
|
|
14
|
-
|
|
15
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|z|[+-]\d{2}:\d{2})$/.test(value) || !Number.isFinite(Date.parse(value))) throw new Error("Invalid history timestamp");
|
|
16
|
+
const normalized = normalizeTimestampForCursor(value, "after");
|
|
17
|
+
if (!normalized || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z$/.test(normalized)) throw new Error("Invalid history timestamp");
|
|
18
|
+
return normalized;
|
|
19
|
+
}
|
|
20
|
+
const INBOX_FORBIDDEN_KEYS = new Set<string>([
|
|
21
|
+
"__proto__",
|
|
22
|
+
"prototype",
|
|
23
|
+
...Object.getOwnPropertyNames(Object.prototype),
|
|
24
|
+
...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
|
|
25
|
+
]);
|
|
26
|
+
const isInboxForbiddenKey = (key: string) => INBOX_FORBIDDEN_KEYS.has(key) || INBOX_FORBIDDEN_KEYS.has(key.toLowerCase());
|
|
27
|
+
function validChannel(channel: unknown): channel is string {
|
|
28
|
+
return typeof channel === "string" && channel.length > 0 && channel.length <= 128 && channel === channel.trim() && channel !== "."
|
|
29
|
+
&& !channel.includes("..") && !/[\/\\]/.test(channel)
|
|
30
|
+
&& !/%(?:2e%2e|2f|5c|00)/i.test(channel)
|
|
31
|
+
&& !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel)
|
|
32
|
+
&& !isInboxForbiddenKey(channel);
|
|
33
|
+
}
|
|
34
|
+
function validHistoryMessageId(id: unknown): id is string {
|
|
35
|
+
return typeof id === "string" && id.length > 0 && id.length <= 256 && id === id.trim() && id !== "."
|
|
36
|
+
&& !id.includes("..") && !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(id)
|
|
37
|
+
&& !/%(?:2e%2e|2f|5c|00)/i.test(id) && !isInboxForbiddenKey(id);
|
|
38
|
+
}
|
|
39
|
+
function validateChannel(channel: unknown): asserts channel is string {
|
|
40
|
+
if (!validChannel(channel)) throw new Error("Invalid inbound channel");
|
|
15
41
|
}
|
|
16
42
|
|
|
17
43
|
/** REST checkpoints, independent of live WS delivery. Advancing a live cursor
|
|
@@ -24,19 +50,49 @@ export class InboxSync {
|
|
|
24
50
|
constructor(stateDir: string, private api: (path: string) => Promise<any>,
|
|
25
51
|
private receive: (message: unknown) => boolean, private active: () => boolean,
|
|
26
52
|
private log: (message: string) => void = console.error) {
|
|
53
|
+
const existing = lstatSync(stateDir, { throwIfNoEntry: false });
|
|
54
|
+
if (existing && (existing.isSymbolicLink() || !existing.isDirectory())) throw new Error("Invalid inbound state directory");
|
|
55
|
+
assertDirectoryAncestors(stateDir);
|
|
27
56
|
mkdirSync(stateDir, {recursive:true, mode:0o700});
|
|
57
|
+
const dirStat = lstatSync(stateDir);
|
|
58
|
+
if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) throw new Error("Invalid inbound state directory");
|
|
59
|
+
if (process.platform !== "win32") chmodSync(stateDir, 0o700);
|
|
28
60
|
this.file = join(stateDir, "inbound-cursors.json");
|
|
29
|
-
|
|
30
|
-
|
|
61
|
+
let fileStat;
|
|
62
|
+
try { fileStat = lstatSync(this.file); }
|
|
63
|
+
catch (err) { if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err; }
|
|
64
|
+
if (fileStat && (fileStat.isSymbolicLink() || !fileStat.isFile())) throw new Error("Invalid inbound cursors file");
|
|
65
|
+
if (fileStat && fileStat.size > 1_048_576) throw new Error("Inbound cursors exceed size limit");
|
|
66
|
+
this.state = fileStat ? JSON.parse(readFileSync(this.file, "utf8")) : {version:1, channels:{}};
|
|
67
|
+
if (!this.state || typeof this.state !== "object" || Array.isArray(this.state) || Object.hasOwn(this.state, "__proto__") || this.state.version !== 1 || !this.state.channels || typeof this.state.channels !== "object" || Array.isArray(this.state.channels) ||
|
|
68
|
+
Object.hasOwn(this.state.channels, "__proto__") || Object.keys(this.state.channels).length > 1024)
|
|
31
69
|
throw new Error("Invalid inbound cursors; refusing to discard checkpoint");
|
|
32
|
-
|
|
33
|
-
|
|
70
|
+
const channels: Record<string, string> = Object.create(null);
|
|
71
|
+
for (const [channel, value] of Object.entries(this.state.channels)) {
|
|
72
|
+
if (!validChannel(channel)) continue;
|
|
73
|
+
timestamp(value);
|
|
74
|
+
channels[channel] = value;
|
|
75
|
+
}
|
|
76
|
+
this.state.channels = channels;
|
|
34
77
|
}
|
|
35
78
|
private save() {
|
|
36
|
-
|
|
37
|
-
|
|
79
|
+
const tmp = `${this.file}.${process.pid}.${Date.now()}.${randomBytes(4).toString("hex")}.tmp`;
|
|
80
|
+
let created = false;
|
|
81
|
+
try {
|
|
82
|
+
writeFileSync(tmp, JSON.stringify(this.state), {mode:0o600, flag:"wx"});
|
|
83
|
+
created = true;
|
|
84
|
+
atomicReplaceRegularFile(tmp, this.file, () => {
|
|
85
|
+
const current = lstatSync(this.file, { throwIfNoEntry: false });
|
|
86
|
+
if (current && (current.isSymbolicLink() || !current.isFile())) throw new Error("Invalid inbound cursors file");
|
|
87
|
+
});
|
|
88
|
+
} catch (err) {
|
|
89
|
+
if (created) { try { unlinkSync(tmp); } catch {} }
|
|
90
|
+
throw err;
|
|
91
|
+
}
|
|
38
92
|
}
|
|
39
93
|
watch(channel: string) {
|
|
94
|
+
validateChannel(channel);
|
|
95
|
+
if (!Object.hasOwn(this.state.channels, channel) && Object.keys(this.state.channels).length >= 1024) throw new Error("Inbound channel limit exceeded");
|
|
40
96
|
this.channels.add(channel);
|
|
41
97
|
// First installation/new membership starts now, never replays old requests.
|
|
42
98
|
if (!Object.hasOwn(this.state.channels, channel)) {
|
|
@@ -44,8 +100,17 @@ export class InboxSync {
|
|
|
44
100
|
}
|
|
45
101
|
}
|
|
46
102
|
memberships(channels: string[]) {
|
|
47
|
-
|
|
48
|
-
|
|
103
|
+
for (const channel of channels) validateChannel(channel);
|
|
104
|
+
if (new Set([...Object.keys(this.state.channels), ...channels]).size > 1024) throw new Error("Inbound channel limit exceeded");
|
|
105
|
+
this.channels = new Set(channels);
|
|
106
|
+
let changed = false;
|
|
107
|
+
for (const channel of this.channels) {
|
|
108
|
+
if (!Object.hasOwn(this.state.channels, channel)) {
|
|
109
|
+
this.state.channels[channel] = timestamp(new Date().toISOString());
|
|
110
|
+
changed = true;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (changed) this.save();
|
|
49
114
|
}
|
|
50
115
|
sync(): Promise<void> {
|
|
51
116
|
if (!this.running) this.running = this.run().finally(() => {this.running = undefined;});
|
|
@@ -64,7 +129,7 @@ export class InboxSync {
|
|
|
64
129
|
const messages = Array.isArray(body) ? body : body?.messages;
|
|
65
130
|
if (!Array.isArray(messages)) throw new Error("Invalid history response");
|
|
66
131
|
const rows = messages.map(m => {
|
|
67
|
-
if (!m || m.channel_id !== channel ||
|
|
132
|
+
if (!m || typeof m !== "object" || Object.hasOwn(m, "__proto__") || m.channel_id !== channel || !validHistoryMessageId(m.id)) throw new Error("Invalid history message");
|
|
68
133
|
return {message:m, time:timestamp(m.timestamp)};
|
|
69
134
|
}).sort((a,b) => a.time.localeCompare(b.time));
|
|
70
135
|
// One bounded page per channel per pass. Full pages continue next pass.
|
package/codex/loop-grants.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { lstatSync, readFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import { assertDirectoryAncestors } from "./config.ts";
|
|
3
4
|
import type { BridgeConfig } from "./config.ts";
|
|
4
5
|
|
|
5
6
|
export interface LoopGrant {
|
|
@@ -18,26 +19,61 @@ export interface LoopTick {
|
|
|
18
19
|
prompt: string;
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
const GRANT_FORBIDDEN_KEYS = new Set<string>([
|
|
23
|
+
"__proto__",
|
|
24
|
+
"prototype",
|
|
25
|
+
...Object.getOwnPropertyNames(Object.prototype),
|
|
26
|
+
...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
|
|
27
|
+
]);
|
|
28
|
+
const isGrantForbiddenKey = (key: string) => GRANT_FORBIDDEN_KEYS.has(key) || GRANT_FORBIDDEN_KEYS.has(key.toLowerCase());
|
|
29
|
+
const ownProto = (value: any) => Boolean(value && typeof value === "object" && Object.prototype.hasOwnProperty.call(value, "__proto__"));
|
|
30
|
+
|
|
21
31
|
// An operator writes this local authorization only after an explicit owner request.
|
|
22
32
|
// Neither chat content nor a server-created loop alone grants local execution.
|
|
23
|
-
function grants(
|
|
33
|
+
function grants(
|
|
34
|
+
config: BridgeConfig,
|
|
35
|
+
opts?: { platform?: NodeJS.Platform; getuid?: (() => number) | undefined },
|
|
36
|
+
): LoopGrant[] {
|
|
24
37
|
try {
|
|
38
|
+
const platform = opts?.platform ?? process.platform;
|
|
39
|
+
const getuid = opts && "getuid" in opts ? opts.getuid : process.getuid;
|
|
40
|
+
assertDirectoryAncestors(config.stateDir);
|
|
41
|
+
const directory = lstatSync(config.stateDir);
|
|
42
|
+
if (directory.isSymbolicLink() || !directory.isDirectory()) return [];
|
|
25
43
|
const file = join(config.stateDir, "loop-grants.json"), stat = lstatSync(file);
|
|
26
|
-
if (
|
|
44
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1_048_576) return [];
|
|
45
|
+
if (platform !== "win32") {
|
|
46
|
+
if (typeof getuid !== "function" || (stat.mode & 0o077) !== 0 || stat.uid !== getuid()) return [];
|
|
47
|
+
}
|
|
27
48
|
const doc = JSON.parse(readFileSync(file, "utf8"));
|
|
28
|
-
if (doc?.version !== 1 || !Array.isArray(doc.grants)) return [];
|
|
29
|
-
|
|
49
|
+
if (doc?.version !== 1 || ownProto(doc) || !Array.isArray(doc.grants) || doc.grants.length > 256) return [];
|
|
50
|
+
const safeId = (value: unknown): value is string => typeof value === "string" && value.length > 0 &&
|
|
51
|
+
value.length <= 128 && value.trim() === value && value !== "." && !value.includes("..") &&
|
|
52
|
+
!/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) &&
|
|
53
|
+
!isGrantForbiddenKey(value);
|
|
54
|
+
const safeOwnerId = (value: unknown): value is string => typeof value === "string" && value.length > 0 &&
|
|
55
|
+
value.length <= 254 && value.trim() === value && value !== "." && !value.includes("..") &&
|
|
56
|
+
!/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) &&
|
|
57
|
+
!isGrantForbiddenKey(value);
|
|
58
|
+
return doc.grants.filter((g: any) => g && !ownProto(g) &&
|
|
30
59
|
[g.loop_id, g.channel_id, g.agent_id, g.owner_id, g.prompt].every(v => typeof v === "string" && v.trim()) &&
|
|
60
|
+
/^loop_[A-Za-z0-9_-]+$/.test(g.loop_id) &&
|
|
61
|
+
[g.loop_id, g.channel_id, g.agent_id].every(safeId) &&
|
|
62
|
+
safeOwnerId(g.owner_id) &&
|
|
31
63
|
g.agent_id === config.agentId && g.prompt.length <= 4000 &&
|
|
32
64
|
Number.isSafeInteger(g.interval_ms) && g.interval_ms >= 60_000 && g.interval_ms <= 86_400_000);
|
|
33
65
|
} catch { return []; }
|
|
34
66
|
}
|
|
35
67
|
|
|
36
|
-
export function authorizedLoopTick(
|
|
68
|
+
export function authorizedLoopTick(
|
|
69
|
+
raw: any,
|
|
70
|
+
config: BridgeConfig,
|
|
71
|
+
opts?: { platform?: NodeJS.Platform; getuid?: (() => number) | undefined },
|
|
72
|
+
): LoopGrant | null {
|
|
37
73
|
const tick = raw?.meta;
|
|
38
74
|
if (raw?.sender_id !== config.agentId || tick?.kind !== "loop_tick" ||
|
|
39
75
|
!Number.isSafeInteger(tick.next_tick_ms) || tick.next_tick_ms <= 0) return null;
|
|
40
|
-
const matches = grants(config).filter(g => g.loop_id === tick.loop_id && g.channel_id === raw.channel_id);
|
|
76
|
+
const matches = grants(config, opts).filter(g => g.loop_id === tick.loop_id && g.channel_id === raw.channel_id);
|
|
41
77
|
if (matches.length !== 1) return null;
|
|
42
78
|
const grant = matches[0]!;
|
|
43
79
|
if (tick.prompt !== grant.prompt || tick.interval_ms !== grant.interval_ms ||
|
|
@@ -47,20 +83,22 @@ export function authorizedLoopTick(raw: any, config: BridgeConfig): LoopGrant |
|
|
|
47
83
|
}
|
|
48
84
|
|
|
49
85
|
export async function verifyLoopTick(raw: any, config: BridgeConfig, owner: string | null,
|
|
50
|
-
list: () => Promise<unknown
|
|
51
|
-
|
|
86
|
+
list: () => Promise<unknown>,
|
|
87
|
+
opts?: { platform?: NodeJS.Platform; getuid?: (() => number) | undefined }): Promise<LoopGrant | null> {
|
|
88
|
+
const grant = authorizedLoopTick(raw, config, opts);
|
|
52
89
|
if (!grant || owner !== grant.owner_id || config.permissions !== "full-access") return null;
|
|
53
90
|
let response: any;
|
|
54
91
|
try { response = await list(); } catch { return null; }
|
|
55
|
-
const rows = Array.isArray(response?.loops) ? response.loops.filter((r: any) => r?.loop_id === grant.loop_id) : [];
|
|
92
|
+
const rows = Array.isArray(response?.loops) && response.loops.length <= 1024 ? response.loops.filter((r: any) => r?.loop_id === grant.loop_id) : [];
|
|
56
93
|
if (rows.length !== 1) return null;
|
|
57
94
|
const loop = rows[0];
|
|
58
|
-
if (loop.status !== "active" || loop.channel_id !== grant.channel_id || loop.prompt !== grant.prompt ||
|
|
95
|
+
if (!loop || ownProto(loop) || loop.status !== "active" || loop.channel_id !== grant.channel_id || loop.prompt !== grant.prompt ||
|
|
59
96
|
loop.interval_ms !== grant.interval_ms || loop.expires_at !== null ||
|
|
60
97
|
(loop.mode !== undefined && loop.mode !== "static") ||
|
|
61
98
|
!Number.isSafeInteger(loop.last_tick_at) || loop.last_tick_at <= 0 ||
|
|
99
|
+
!Number.isSafeInteger(loop.next_tick_ms) ||
|
|
62
100
|
loop.next_tick_ms !== raw.meta.next_tick_ms || loop.last_tick_at + grant.interval_ms !== loop.next_tick_ms) return null;
|
|
63
101
|
// Re-read after network I/O so local revocation during verification takes effect.
|
|
64
|
-
const current = authorizedLoopTick(raw, config);
|
|
102
|
+
const current = authorizedLoopTick(raw, config, opts);
|
|
65
103
|
return current && current.owner_id === owner ? current : null;
|
|
66
104
|
}
|
package/codex/manager.ts
CHANGED
|
@@ -1,46 +1,91 @@
|
|
|
1
1
|
import { spawn, type ChildProcess } from "node:child_process";
|
|
2
|
-
import { mkdirSync, openSync, closeSync, readFileSync, writeFileSync, unlinkSync,
|
|
3
|
-
import { join, resolve } from "node:path";
|
|
2
|
+
import { mkdirSync, openSync, closeSync, readFileSync, writeFileSync, unlinkSync, lstatSync } from "node:fs";
|
|
3
|
+
import { join, resolve, dirname } from "node:path";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
6
7
|
import { parseArgs } from "node:util";
|
|
7
8
|
import { loadBots, defaultRegistry, type BotConfig } from "./bots-config.ts";
|
|
9
|
+
import { assertDirectoryAncestors, atomicReplaceRegularFile } from "./config.ts";
|
|
8
10
|
import { codexPresent } from "./processes.ts";
|
|
9
|
-
|
|
10
|
-
const root = join(homedir(), ".agentschat/codex-bots")
|
|
11
|
+
let values: { config?: string; "watch-codex"?: boolean; check?: boolean; status?: boolean; help?: boolean } = {};
|
|
12
|
+
const root = join(homedir(), ".agentschat/codex-bots");
|
|
13
|
+
let registry = "";
|
|
11
14
|
const statusFile = join(root, "status.json"), lock = join(root, "manager.lock");
|
|
12
|
-
interface Worker { child?: ChildProcess; config: BotConfig; fingerprint: string; failures: number; next: number; status: string }
|
|
15
|
+
export interface Worker { child?: ChildProcess; config: BotConfig; fingerprint: string; failures: number; next: number; status: string }
|
|
13
16
|
const workers = new Map<string, Worker>();
|
|
14
|
-
let stopping = false, missing = 0, timer: ReturnType<typeof setTimeout> | undefined;
|
|
15
|
-
function removeDeadLock(file: string) {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
let stopping = false, missing = 0, saveSeq = 0, timer: ReturnType<typeof setTimeout> | undefined;
|
|
18
|
+
export function removeDeadLock(file: string) {
|
|
19
|
+
let raw: string;
|
|
20
|
+
try {
|
|
21
|
+
assertDirectoryAncestors(dirname(file));
|
|
22
|
+
const stat = lstatSync(file);
|
|
23
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 64 * 1024) return;
|
|
24
|
+
raw = readFileSync(file, "utf8").trim();
|
|
25
|
+
} catch { return; }
|
|
26
|
+
const pid = Number(raw);
|
|
27
|
+
if (!/^\d+$/.test(raw) || !Number.isSafeInteger(pid) || pid <= 0) {
|
|
28
|
+
try { unlinkSync(file); } catch {}
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
try { process.kill(pid, 0); } catch (e: any) { if (e.code === "ESRCH") try { unlinkSync(file); } catch {} }
|
|
20
32
|
}
|
|
21
|
-
function save() {
|
|
22
|
-
|
|
23
|
-
|
|
33
|
+
export function save(rootDir = root) {
|
|
34
|
+
const statusFile = join(rootDir, "status.json");
|
|
35
|
+
const tmp = `${statusFile}.${process.pid}.${++saveSeq}.tmp`;
|
|
36
|
+
let created = false;
|
|
37
|
+
try {
|
|
38
|
+
assertDirectoryAncestors(rootDir);
|
|
39
|
+
const dir = lstatSync(rootDir);
|
|
40
|
+
if (dir.isSymbolicLink() || !dir.isDirectory()) return;
|
|
41
|
+
try { if (lstatSync(statusFile).isSymbolicLink()) return; }
|
|
42
|
+
catch (e: any) { if (e.code !== "ENOENT") return; }
|
|
43
|
+
writeFileSync(tmp, JSON.stringify({ pid: process.pid, updated_at: new Date().toISOString(), bots: [...workers.values()].map(w => ({ name: w.config.name, agent_id: w.config.agentId, workdir: w.config.cwd, effort: w.config.effort, model: w.config.model, pid: w.child?.pid, status: w.status })) }, null, 2), { mode: 0o600, flag: "wx" });
|
|
44
|
+
created = true;
|
|
45
|
+
atomicReplaceRegularFile(tmp, statusFile, () => {
|
|
46
|
+
assertDirectoryAncestors(rootDir);
|
|
47
|
+
const currentDir = lstatSync(rootDir);
|
|
48
|
+
const currentFile = lstatSync(statusFile, { throwIfNoEntry: false });
|
|
49
|
+
if (currentDir.isSymbolicLink() || !currentDir.isDirectory() ||
|
|
50
|
+
(currentFile && (currentFile.isSymbolicLink() || !currentFile.isFile()))) throw new Error("Unsafe status destination");
|
|
51
|
+
});
|
|
52
|
+
} catch {
|
|
53
|
+
if (created) try { unlinkSync(tmp); } catch {}
|
|
54
|
+
}
|
|
24
55
|
}
|
|
25
|
-
async function stop(w: Worker) {
|
|
56
|
+
export async function stop(w: Worker) {
|
|
26
57
|
const child = w.child;
|
|
27
58
|
if (child && child.exitCode === null && child.signalCode === null) await new Promise<void>(done => {
|
|
28
59
|
const timeout = setTimeout(() => killGroup(child), 20_000);
|
|
29
|
-
|
|
60
|
+
timeout.unref?.();
|
|
61
|
+
const exited = () => { clearTimeout(timeout); killGroup(child); done(); };
|
|
62
|
+
child.once("exit", exited);
|
|
63
|
+
try { child.kill("SIGTERM"); }
|
|
64
|
+
catch { clearTimeout(timeout); child.removeListener("exit", exited); done(); }
|
|
30
65
|
});
|
|
31
66
|
w.child = undefined; w.status = "stopped";
|
|
32
67
|
}
|
|
33
|
-
function killGroup(child: ChildProcess) {
|
|
34
|
-
|
|
68
|
+
function killGroup(child: ChildProcess) {
|
|
69
|
+
if (!child.pid) return;
|
|
70
|
+
if (process.platform !== "win32") {
|
|
71
|
+
try { process.kill(-child.pid, "SIGKILL"); return; } catch {}
|
|
72
|
+
}
|
|
73
|
+
try { child.kill("SIGKILL"); } catch {}
|
|
74
|
+
}
|
|
75
|
+
export function start(w: Worker, spawnWorker = spawn) {
|
|
35
76
|
removeDeadLock(join(w.config.stateDir, "bridge.lock")); w.status = "starting";
|
|
36
|
-
const child =
|
|
77
|
+
const child = spawnWorker(process.execPath, [resolve(process.argv[1]!), "--codex-bridge", "--managed-worker"], { cwd: w.config.cwd, detached: process.platform !== "win32", windowsHide: true, stdio: ["ignore", "pipe", "pipe", "ipc"] });
|
|
37
78
|
w.child = child;
|
|
38
|
-
child.once("spawn", () =>
|
|
79
|
+
child.once("spawn", () => {
|
|
80
|
+
if (child.connected) try { child.send(w.config, () => {}); } catch {}
|
|
81
|
+
});
|
|
39
82
|
let buffer = "";
|
|
83
|
+
const escapedAgentId = w.config.agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
84
|
+
const connectedRe = new RegExp(`(?:^|[\\r\\n])AgentsChat connected as ${escapedAgentId}(?![A-Za-z0-9_.-])`);
|
|
40
85
|
child.stderr?.on("data", data => {
|
|
41
86
|
buffer = (buffer + String(data)).slice(-8192);
|
|
42
|
-
if (
|
|
43
|
-
else if (
|
|
87
|
+
if (connectedRe.test(buffer)) { w.status = "connected"; w.failures = 0; buffer = ""; save(); }
|
|
88
|
+
else if (/(?:^|[\r\n]).*\bdisconnected\b/i.test(buffer)) { w.status = "reconnecting"; buffer = ""; save(); }
|
|
44
89
|
});
|
|
45
90
|
child.stdout?.resume();
|
|
46
91
|
const failed = () => { if (w.child !== child) return; killGroup(child); w.child = undefined; w.status = "retrying"; w.next = Date.now() + Math.min(60_000, 1000 * 2 ** Math.min(++w.failures, 6)); save(); };
|
|
@@ -61,21 +106,57 @@ async function tick() {
|
|
|
61
106
|
missing = active ? 0 : missing + 1;
|
|
62
107
|
for (const w of workers.values()) {
|
|
63
108
|
if (stopping) break;
|
|
64
|
-
|
|
109
|
+
const now = Date.now();
|
|
110
|
+
if (w.next - now > 60_000) w.next = now + 60_000;
|
|
111
|
+
if (active && !w.child && now >= w.next) start(w);
|
|
65
112
|
else if (!active && missing >= 2 && w.child) await stop(w);
|
|
66
113
|
}
|
|
67
114
|
save();
|
|
68
115
|
}
|
|
116
|
+
export function removeOwnedLock(file: string) {
|
|
117
|
+
try {
|
|
118
|
+
assertDirectoryAncestors(dirname(file));
|
|
119
|
+
const stat = lstatSync(file);
|
|
120
|
+
if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024 && readFileSync(file, "utf8").trim() === String(process.pid)) unlinkSync(file);
|
|
121
|
+
} catch {}
|
|
122
|
+
}
|
|
69
123
|
async function main() {
|
|
70
124
|
if (values.help) { console.log("agentschat-mcp --codex-bots [--config FILE] [--watch-codex] [--check|--status]\nCentral registry: ~/.agentschat/codex-bots.json; profiles: ~/.agentschat/profiles\nWatch polls external Codex processes every 5 seconds."); return; }
|
|
71
|
-
if (values.status) {
|
|
125
|
+
if (values.status) {
|
|
126
|
+
try {
|
|
127
|
+
assertDirectoryAncestors(root);
|
|
128
|
+
const stat = lstatSync(statusFile);
|
|
129
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1_048_576) throw new Error("Unsafe status file");
|
|
130
|
+
const raw = readFileSync(statusFile, "utf8"), status = JSON.parse(raw);
|
|
131
|
+
if (!status || typeof status !== "object" || Array.isArray(status) ||
|
|
132
|
+
Object.prototype.hasOwnProperty.call(status, "__proto__") ||
|
|
133
|
+
(status.pid !== undefined && (typeof status.pid !== "number" || !Number.isSafeInteger(status.pid) || status.pid <= 0)) ||
|
|
134
|
+
!Array.isArray(status.bots) ||
|
|
135
|
+
status.bots.some((b: unknown) => !b || typeof b !== "object" || Array.isArray(b) || Object.prototype.hasOwnProperty.call(b, "__proto__"))) throw new Error("Invalid status file");
|
|
136
|
+
console.log(raw);
|
|
137
|
+
} catch { console.error("Bot manager status unavailable; status file is missing, unsafe, or unreadable"); process.exitCode = 1; }
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
72
140
|
const configs = loadBots(registry);
|
|
73
141
|
if (values.check) { console.log(JSON.stringify(configs.map(c => ({ name: c.name, agent_id: c.agentId, workdir: c.cwd, profile: c.profileFile })))); return; }
|
|
74
|
-
|
|
142
|
+
for (const directory of [join(homedir(), ".agentschat"), root]) {
|
|
143
|
+
const stat = lstatSync(directory, { throwIfNoEntry: false });
|
|
144
|
+
if (stat && (stat.isSymbolicLink() || !stat.isDirectory())) throw new Error("Unsafe manager directory");
|
|
145
|
+
}
|
|
146
|
+
assertDirectoryAncestors(root);
|
|
147
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
148
|
+
const dir = lstatSync(root);
|
|
149
|
+
if (dir.isSymbolicLink() || !dir.isDirectory()) throw new Error("Unsafe manager directory");
|
|
150
|
+
removeDeadLock(lock);
|
|
151
|
+
if (lstatSync(lock, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error("Unsafe manager lock");
|
|
75
152
|
const fd = openSync(lock, "wx", 0o600); writeFileSync(fd, String(process.pid)); closeSync(fd);
|
|
76
153
|
let running: Promise<void> = Promise.resolve();
|
|
77
154
|
const loop = () => { running = tick().catch(() => console.error("Supervisor tick failed")).finally(() => { if (!stopping) timer = setTimeout(loop, 5000); }); };
|
|
78
|
-
const shutdown = async () => { if (stopping) return; stopping = true; clearTimeout(timer); await running; await Promise.all([...workers.values()].map(stop)); save();
|
|
155
|
+
const shutdown = async () => { if (stopping) return; stopping = true; clearTimeout(timer); await running; await Promise.all([...workers.values()].map(stop)); save(); removeOwnedLock(lock); };
|
|
79
156
|
process.once("SIGINT", () => void shutdown()); process.once("SIGTERM", () => void shutdown()); loop();
|
|
80
157
|
}
|
|
81
|
-
|
|
158
|
+
if (import.meta.main || process.argv.includes("--codex-bots") || (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url))) {
|
|
159
|
+
({ values } = parseArgs({ options: { "codex-bots": { type: "boolean" }, config: { type: "string" }, "watch-codex": { type: "boolean" }, check: { type: "boolean" }, status: { type: "boolean" }, help: { type: "boolean" } } }));
|
|
160
|
+
registry = resolve(values.config ?? defaultRegistry());
|
|
161
|
+
main().catch(() => { console.error("Bot manager failed; check registry, profile permissions, and existing manager"); process.exitCode = 1; });
|
|
162
|
+
}
|
package/codex/owner.ts
CHANGED
|
@@ -1,3 +1,79 @@
|
|
|
1
|
+
const OWNER_FORBIDDEN_KEYS = new Set<string>([
|
|
2
|
+
"__proto__",
|
|
3
|
+
"prototype",
|
|
4
|
+
...Object.getOwnPropertyNames(Object.prototype),
|
|
5
|
+
...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
|
|
6
|
+
]);
|
|
7
|
+
const isOwnerForbiddenKey = (key: string) => OWNER_FORBIDDEN_KEYS.has(key) || OWNER_FORBIDDEN_KEYS.has(key.toLowerCase());
|
|
8
|
+
|
|
9
|
+
/** URL parsing canonicalizes numeric IPv4 and mapped IPv6 before this check. */
|
|
10
|
+
export function blockedServerHost(url: URL): boolean {
|
|
11
|
+
const host = url.hostname.toLowerCase().replace(/\.+$/, "").replace(/^\[|\]$/g, "");
|
|
12
|
+
if (!host || host === "0.0.0.0" || /^0\./.test(host) || host === "::" || host === "0:0:0:0:0:0:0:0" ||
|
|
13
|
+
/^169\.254\./.test(host) || host === "100.100.100.200" ||
|
|
14
|
+
/^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d{1,3}\.\d{1,3}$/.test(host) ||
|
|
15
|
+
host === "fd00:ec2::254" || host === "fd00:ec2:0:0:0:0:0:254" ||
|
|
16
|
+
host === "metadata" || host === "instance-data" ||
|
|
17
|
+
host === "metadata.google.internal" || host.endsWith(".metadata.google.internal") ||
|
|
18
|
+
host === "metadata.goog" || host.endsWith(".metadata.goog") ||
|
|
19
|
+
/^fe[89ab][0-9a-f]:/.test(host)) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
if (host.startsWith("::ffff:")) {
|
|
23
|
+
const rawTail = host.slice(7);
|
|
24
|
+
if (rawTail === "0:0" || rawTail === "0.0.0.0") return true;
|
|
25
|
+
const tail = /^0:(?:[0-9a-f]{1,4}:|\d{1,3}\.)/.test(rawTail) ? rawTail.slice(2) : rawTail;
|
|
26
|
+
if (tail === "0:0" || tail === "0.0.0.0" || /^0\./.test(tail) || /^[0-9a-f]{1,2}:[0-9a-f]{1,4}$/.test(tail) ||
|
|
27
|
+
/^127\./.test(tail) || /^7f[0-9a-f]{2}:/.test(tail) ||
|
|
28
|
+
/^169\.254\./.test(tail) || /^a9fe:/.test(tail) ||
|
|
29
|
+
tail === "100.100.100.200" || /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d{1,3}\.\d{1,3}$/.test(tail) || tail === "6464:64c8") {
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
const hexMatch = tail.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
|
|
33
|
+
if (hexMatch) {
|
|
34
|
+
const hi = parseInt(hexMatch[1]!, 16);
|
|
35
|
+
const lo = parseInt(hexMatch[2]!, 16);
|
|
36
|
+
const firstOctet = (hi >> 8) & 0xff;
|
|
37
|
+
const secondOctet = hi & 0xff;
|
|
38
|
+
if (
|
|
39
|
+
firstOctet === 0 ||
|
|
40
|
+
firstOctet === 127 ||
|
|
41
|
+
(firstOctet === 169 && secondOctet === 254) ||
|
|
42
|
+
(firstOctet === 100 && (secondOctet & 0xc0) === 0x40) ||
|
|
43
|
+
(hi === 0x6464 && lo === 0x64c8)
|
|
44
|
+
) {
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Read bounded response bytes before decoding or parsing untrusted JSON. */
|
|
53
|
+
async function ownerJson(response: Response): Promise<unknown> {
|
|
54
|
+
if (!response.body) throw new Error("Missing owner response");
|
|
55
|
+
const reader = response.body.getReader();
|
|
56
|
+
const chunks: Uint8Array[] = [];
|
|
57
|
+
let size = 0;
|
|
58
|
+
try {
|
|
59
|
+
while (true) {
|
|
60
|
+
const { done, value } = await reader.read();
|
|
61
|
+
if (done) break;
|
|
62
|
+
size += value.byteLength;
|
|
63
|
+
if (size > 65_536) {
|
|
64
|
+
// Cancel without awaiting a possibly stalled transport cancellation.
|
|
65
|
+
void reader.cancel().catch(() => {});
|
|
66
|
+
throw new Error("Owner response exceeds size limit");
|
|
67
|
+
}
|
|
68
|
+
chunks.push(value);
|
|
69
|
+
}
|
|
70
|
+
} finally { reader.releaseLock(); }
|
|
71
|
+
const bytes = new Uint8Array(size);
|
|
72
|
+
let offset = 0;
|
|
73
|
+
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
|
|
74
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
75
|
+
}
|
|
76
|
+
|
|
1
77
|
/** Resolve only this authenticated bot's owner; callers must compare sender IDs. */
|
|
2
78
|
export async function getBotOwner(
|
|
3
79
|
base: string,
|
|
@@ -6,7 +82,16 @@ export async function getBotOwner(
|
|
|
6
82
|
request: typeof fetch = fetch,
|
|
7
83
|
): Promise<string | null> {
|
|
8
84
|
try {
|
|
9
|
-
|
|
85
|
+
if (!base || base !== base.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(base) ||
|
|
86
|
+
!agentId || agentId !== agentId.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(agentId) ||
|
|
87
|
+
/%(?:2e%2e|2f|5c|00)/i.test(agentId) ||
|
|
88
|
+
agentId === "." || agentId.includes("..") || isOwnerForbiddenKey(agentId) || /[\/\\\s]/.test(agentId) ||
|
|
89
|
+
!token || token !== token.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(token)) return null;
|
|
90
|
+
const parsed = new URL(base);
|
|
91
|
+
const loopback = ["127.0.0.1", "localhost", "[::1]", "::1"].includes(parsed.hostname.toLowerCase().replace(/\.$/, ""));
|
|
92
|
+
if (blockedServerHost(parsed) || (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && loopback)) ||
|
|
93
|
+
parsed.username || parsed.password || parsed.search || parsed.hash || parsed.port === "0") return null;
|
|
94
|
+
const origin = parsed.href.replace(/\/+$/, "");
|
|
10
95
|
const options: RequestInit = {
|
|
11
96
|
method: "GET",
|
|
12
97
|
headers: { Authorization: `Bearer ${token}` },
|
|
@@ -14,19 +99,31 @@ export async function getBotOwner(
|
|
|
14
99
|
redirect: "error",
|
|
15
100
|
signal: AbortSignal.timeout(8_000),
|
|
16
101
|
};
|
|
17
|
-
const [
|
|
102
|
+
const [statusSettled, entitlementSettled] = await Promise.allSettled([
|
|
18
103
|
request(`${origin}/api/account/onboarding`, options),
|
|
19
104
|
request(`${origin}/api/me/entitlements`, options),
|
|
20
105
|
]);
|
|
21
|
-
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
106
|
+
const statusResponse = statusSettled.status === "fulfilled" ? statusSettled.value : null;
|
|
107
|
+
const entitlementResponse = entitlementSettled.status === "fulfilled" ? entitlementSettled.value : null;
|
|
108
|
+
if (!statusResponse?.ok || !entitlementResponse?.ok) {
|
|
109
|
+
await Promise.allSettled([
|
|
110
|
+
statusResponse?.body?.cancel(),
|
|
111
|
+
entitlementResponse?.body?.cancel(),
|
|
112
|
+
]);
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
const [statusValue, entitlementValue] = await Promise.all([
|
|
116
|
+
ownerJson(statusResponse),
|
|
117
|
+
ownerJson(entitlementResponse),
|
|
25
118
|
]);
|
|
26
|
-
|
|
27
|
-
|
|
119
|
+
const status = statusValue as Record<string, unknown> | null;
|
|
120
|
+
const entitlement = entitlementValue as Record<string, unknown> | null;
|
|
121
|
+
if (!status || typeof status !== "object" || Array.isArray(status) || Object.hasOwn(status, "__proto__") || status.agent_id !== agentId || status.claimed !== true) return null;
|
|
122
|
+
if (!entitlement || typeof entitlement !== "object" || Array.isArray(entitlement) || Object.hasOwn(entitlement, "__proto__")) return null;
|
|
28
123
|
const owner = entitlement.owner_account_id;
|
|
29
|
-
return typeof owner === "string" && owner.trim().length > 0 && owner
|
|
124
|
+
return typeof owner === "string" && owner.trim().length > 0 && owner === owner.trim() &&
|
|
125
|
+
!/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(owner) && !/%(?:2e%2e|2f|5c|00)/i.test(owner) && owner !== agentId &&
|
|
126
|
+
owner !== "." && !owner.includes("..") && !isOwnerForbiddenKey(owner) ? owner : null;
|
|
30
127
|
} catch {
|
|
31
128
|
// Missing endpoints, failed authentication and unavailable ownership all fail closed.
|
|
32
129
|
// Never retain a previous owner or expose response bodies / credentials in diagnostics.
|
package/codex/processes.ts
CHANGED
|
@@ -1,21 +1,65 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { promisify } from "node:util";
|
|
3
|
-
import { basename } from "node:path";
|
|
4
3
|
|
|
5
4
|
export interface ProcessRow { pid: number; ppid: number; command: string }
|
|
6
5
|
export function parseProcesses(text: string): ProcessRow[] {
|
|
7
|
-
|
|
6
|
+
if (typeof text !== "string" || !text) return [];
|
|
7
|
+
return text.split(/\r?\n/, 65_536).flatMap(line => {
|
|
8
|
+
if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(line)) return [];
|
|
8
9
|
const m = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
|
|
9
|
-
|
|
10
|
+
if (!m) return [];
|
|
11
|
+
const pid = Number(m[1]), ppid = Number(m[2]);
|
|
12
|
+
return Number.isSafeInteger(pid) && pid > 0 && Number.isSafeInteger(ppid) && ppid >= 0
|
|
13
|
+
? [{ pid, ppid, command: m[3]!.trim() }] : [];
|
|
10
14
|
});
|
|
11
15
|
}
|
|
16
|
+
function commandBasename(cmd: string): string {
|
|
17
|
+
const trimmed = cmd.trim();
|
|
18
|
+
const basename = (path: string) => (path.split(/[\\/]/).pop() || "").trim().replace(/\.(?:exe|cmd|bat)$/i, "").toLowerCase();
|
|
19
|
+
if (trimmed.startsWith('"')) {
|
|
20
|
+
const end = trimmed.indexOf('"', 1);
|
|
21
|
+
return end < 0 ? "" : basename(trimmed.slice(1, end));
|
|
22
|
+
}
|
|
23
|
+
const first = trimmed.split(/\s+/, 1)[0]!;
|
|
24
|
+
return basename(first) === "codex" ? "codex" : basename(trimmed);
|
|
25
|
+
}
|
|
12
26
|
export function externalCodexPresent(rows: ProcessRow[], managerPid: number): boolean {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
27
|
+
if (!Array.isArray(rows) || rows.length === 0) return false;
|
|
28
|
+
const children = new Set<number>(Number.isSafeInteger(managerPid) && managerPid > 0 ? [managerPid] : []);
|
|
29
|
+
const byParent = new Map<number, number[]>();
|
|
30
|
+
for (const row of rows) {
|
|
31
|
+
if (!row || !Number.isSafeInteger(row.pid) || row.pid <= 0) continue;
|
|
32
|
+
const ppid = row.ppid;
|
|
33
|
+
if (!Number.isSafeInteger(ppid) || ppid < 0) continue;
|
|
34
|
+
const siblings = byParent.get(ppid);
|
|
35
|
+
if (siblings) siblings.push(row.pid);
|
|
36
|
+
else byParent.set(ppid, [row.pid]);
|
|
37
|
+
}
|
|
38
|
+
const queue = [...children];
|
|
39
|
+
for (let i = 0; i < queue.length; i++) {
|
|
40
|
+
for (const pid of byParent.get(queue[i]!) ?? []) {
|
|
41
|
+
if (children.has(pid)) continue;
|
|
42
|
+
children.add(pid); queue.push(pid);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return rows.some(r => Boolean(r) && typeof r.command === "string" && Number.isSafeInteger(r.pid) && r.pid > 0 && !children.has(r.pid) && commandBasename(r.command) === "codex");
|
|
17
46
|
}
|
|
18
47
|
export async function codexPresent(managerPid = process.pid): Promise<boolean> {
|
|
48
|
+
if (process.platform === "win32") {
|
|
49
|
+
const { stdout } = await promisify(execFile)(
|
|
50
|
+
"powershell.exe",
|
|
51
|
+
[
|
|
52
|
+
"-NoProfile",
|
|
53
|
+
"-NonInteractive",
|
|
54
|
+
"-ExecutionPolicy",
|
|
55
|
+
"Bypass",
|
|
56
|
+
"-Command",
|
|
57
|
+
"Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId) $($_.Name)\" }",
|
|
58
|
+
],
|
|
59
|
+
{ timeout: 5000, maxBuffer: 4 * 1024 * 1024, windowsHide: true },
|
|
60
|
+
);
|
|
61
|
+
return externalCodexPresent(parseProcesses(stdout), managerPid);
|
|
62
|
+
}
|
|
19
63
|
const { stdout } = await promisify(execFile)("/bin/ps", ["-axo", "pid=,ppid=,comm="], { timeout: 5000, maxBuffer: 4 * 1024 * 1024 });
|
|
20
64
|
return externalCodexPresent(parseProcesses(stdout), managerPid);
|
|
21
65
|
}
|