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/bridge.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { ThreadBusyError } from "./app-server.ts";
|
|
2
2
|
import { TEAM_LEAD_SKILL_ID, TEAM_LEAD_SKILL_BODY, TEAM_LEAD_NO_UPDATE, isTeamLeadSkillInvocation } from "../src/team-lead-skill.ts";
|
|
3
|
-
import {
|
|
3
|
+
import { lstatSync, mkdirSync, readFileSync, writeFileSync, openSync, closeSync, unlinkSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
5
6
|
import { priorChannelThreads, preserveChannelHistory, type ThreadHistory } from "./thread-history.ts";
|
|
7
|
+
import { assertDirectoryAncestors, atomicReplaceRegularFile } from "./config.ts";
|
|
6
8
|
import type { BridgeConfig, PermissionMode } from "./config.ts";
|
|
7
9
|
import { redactSecrets } from "../src/redact.ts";
|
|
8
10
|
import { authorizedLoopTick, verifyLoopTick, type LoopTick } from "./loop-grants.ts";
|
|
9
|
-
import { acquireAgentLock, isPidAlive, releaseAgentLock, resolveLockDir } from "../src/session-bind.ts";
|
|
11
|
+
import { acquireAgentLock, checkAgentLock, isPidAlive, releaseAgentLock, resolveLockDir } from "../src/session-bind.ts";
|
|
10
12
|
|
|
11
|
-
export
|
|
13
|
+
export const MAX_BRIDGE_TERMINAL_ENTRIES = 500;
|
|
14
|
+
export interface ChatMessage { id: string; channel_id: string; sender_id: string; content: string; mentions?: string[]; mentioned_ids?: string[]; parent_id?: string; reply_to?: string; meta?: LoopTick }
|
|
12
15
|
interface Entry { message: ChatMessage; status: "pending" | "running" | "ready" | "sending" | "sent" | "failed" | "uncertain" | "blocked" | "skipped"; answer?: string; error?: string }
|
|
13
16
|
interface ChannelThread { thread: string; namespace?: string; bootstrap?: string; importedThreads?: string[] }
|
|
14
17
|
interface State { version: 1; threads: Record<string, string>; channels?: Record<string, ChannelThread>; entries: Entry[] }
|
|
@@ -17,15 +20,38 @@ function permitted(m: ChatMessage, c: BridgeConfig) {
|
|
|
17
20
|
if (m.meta?.kind === "loop_tick") return authorizedLoopTick(m, c) !== null;
|
|
18
21
|
return (!c.channels.length || c.channels.includes(m.channel_id)) && (!c.senders.length || c.senders.includes(m.sender_id));
|
|
19
22
|
}
|
|
23
|
+
const isPrototypeKey = (key: string) => /^(?:__proto__|constructor|prototype)$/i.test(key);
|
|
24
|
+
const cleanBridgeLog = (text: string) => text.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ");
|
|
25
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
26
|
+
return value !== null && typeof value === "object" &&
|
|
27
|
+
(Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
28
|
+
}
|
|
29
|
+
function safeMessageId(value: unknown): value is string {
|
|
30
|
+
return typeof value === "string" && value.length > 0 && value.length <= 256 && value.trim() === value &&
|
|
31
|
+
value !== "." && !value.includes("..") && !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) &&
|
|
32
|
+
!/%(?:2e%2e|2f|5c|00)/i.test(value) && !isPrototypeKey(value);
|
|
33
|
+
}
|
|
34
|
+
function validMentions(value: unknown): boolean {
|
|
35
|
+
return value === undefined || (Array.isArray(value) && value.length <= 128 && [...value].every(id => typeof id === "string"));
|
|
36
|
+
}
|
|
37
|
+
function checkStateDir(dir: string, allowMissing = false) {
|
|
38
|
+
try {
|
|
39
|
+
const stat = lstatSync(dir);
|
|
40
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("Unsafe bridge state directory");
|
|
41
|
+
} catch (error: any) { if (!allowMissing || error.code !== "ENOENT") throw error; }
|
|
42
|
+
assertDirectoryAncestors(dir);
|
|
43
|
+
}
|
|
44
|
+
const entryStatuses = new Set<Entry["status"]>(["pending", "running", "ready", "sending", "sent", "failed", "uncertain", "blocked", "skipped"]);
|
|
20
45
|
export function addressed(m: any, c: BridgeConfig): m is ChatMessage {
|
|
21
|
-
if (!m || ["id", "channel_id", "sender_id", "content"].some(k => typeof m[k] !== "string" || !m[k].trim())) return false;
|
|
46
|
+
if (!isPlainObject(m as unknown) || Object.prototype.hasOwnProperty.call(m, "__proto__") || ["id", "channel_id", "sender_id", "content"].some(k => typeof m[k] !== "string" || !m[k].trim())) return false;
|
|
47
|
+
if (![m.id, m.channel_id, m.sender_id].every(safeMessageId) || !validMentions(m.mentions) || !validMentions(m.mentioned_ids)) return false;
|
|
22
48
|
if (m.content === "__typing__" || m.content.length > 32_000) return false;
|
|
23
49
|
if (["slash_input", "loop_status", "slash_response"].includes(m.meta?.kind)) return false;
|
|
24
50
|
if (m.meta?.kind === "loop_tick") return authorizedLoopTick(m, c) !== null;
|
|
25
51
|
if (m.sender_id === c.agentId) return false;
|
|
26
52
|
if (!permitted(m, c)) return false;
|
|
27
53
|
const escaped = c.agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
28
|
-
return m.channel_id
|
|
54
|
+
return /^dm[-:]/i.test(m.channel_id) || [m.mentions, m.mentioned_ids].some(a => Array.isArray(a) && a.includes(c.agentId)) ||
|
|
29
55
|
new RegExp(`@${escaped}(?![\\w-])|@[^\\n(]+\\(${escaped}\\)`).test(m.content);
|
|
30
56
|
}
|
|
31
57
|
export class Bridge {
|
|
@@ -41,35 +67,98 @@ export class Bridge {
|
|
|
41
67
|
private activity: (channel: string, active: boolean) => void = () => {},
|
|
42
68
|
private owner: () => Promise<string | null> = async () => null,
|
|
43
69
|
private loops: () => Promise<unknown> = async () => null) {
|
|
70
|
+
checkStateDir(config.stateDir, true);
|
|
44
71
|
mkdirSync(config.stateDir, { recursive: true, mode: 0o700 });
|
|
72
|
+
checkStateDir(config.stateDir);
|
|
45
73
|
this.file = join(config.stateDir, "state.json"); this.lock = join(config.stateDir, "bridge.lock");
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
74
|
+
try {
|
|
75
|
+
const stat = lstatSync(this.lock);
|
|
76
|
+
if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024) {
|
|
77
|
+
const content = readFileSync(this.lock, "utf8");
|
|
78
|
+
const holderPid = /^\d+$/.test(content) && content.trim() === content ? Number(content) : NaN;
|
|
79
|
+
if (!Number.isSafeInteger(holderPid) || holderPid <= 0 || !isPidAlive(holderPid)) unlinkSync(this.lock);
|
|
80
|
+
}
|
|
81
|
+
} catch {}
|
|
52
82
|
try { const fd = openSync(this.lock, "wx", 0o600); writeFileSync(fd, String(process.pid)); closeSync(fd); }
|
|
53
83
|
catch { throw new Error(`Bridge already locked: ${this.lock}. If its process has exited, remove that lock manually.`); }
|
|
54
84
|
const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
55
|
-
|
|
56
|
-
lockDir: resolveLockDir(homeDir, process.env),
|
|
57
|
-
agentId: config.agentId,
|
|
58
|
-
runtime: "codex-bridge",
|
|
59
|
-
});
|
|
85
|
+
const lockDir = resolveLockDir(homeDir, process.env);
|
|
60
86
|
try {
|
|
61
|
-
|
|
62
|
-
|
|
87
|
+
let hasState = false;
|
|
88
|
+
try {
|
|
89
|
+
const stat = lstatSync(this.file);
|
|
90
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 16 * 1024 * 1024) throw new Error("Unsafe bridge state");
|
|
91
|
+
hasState = true;
|
|
92
|
+
} catch (error: any) { if (error.code !== "ENOENT") throw error; }
|
|
93
|
+
this.state = hasState ? JSON.parse(readFileSync(this.file, "utf8")) : { version: 1, threads: {}, entries: [] };
|
|
94
|
+
if (this.state?.version !== 1 || Object.prototype.hasOwnProperty.call(this.state, "__proto__") || !isPlainObject(this.state.threads) || Object.prototype.hasOwnProperty.call(this.state.threads, "__proto__") || !Array.isArray(this.state.entries) ||
|
|
95
|
+
(Object.prototype.hasOwnProperty.call(this.state, "channels") && (!isPlainObject(this.state.channels) || Object.prototype.hasOwnProperty.call(this.state.channels, "__proto__")))) throw new Error("Invalid bridge state");
|
|
63
96
|
for (const e of this.state.entries) {
|
|
97
|
+
if (!isPlainObject(e) || Object.prototype.hasOwnProperty.call(e, "__proto__") || !entryStatuses.has(e.status as Entry["status"]) || !isPlainObject(e.message) || Object.prototype.hasOwnProperty.call(e.message, "__proto__") ||
|
|
98
|
+
![e.message.id, e.message.channel_id, e.message.sender_id].every(safeMessageId) || typeof e.message.content !== "string" ||
|
|
99
|
+
!validMentions(e.message.mentions) || !validMentions(e.message.mentioned_ids)) throw new Error("Invalid bridge entry");
|
|
64
100
|
if (e.status === "sending") e.status = "uncertain";
|
|
65
101
|
if (e.status === "running") e.status = "failed";
|
|
66
102
|
}
|
|
67
103
|
this.save();
|
|
68
|
-
} catch {
|
|
104
|
+
} catch {
|
|
105
|
+
try { unlinkSync(this.lock); } catch {}
|
|
106
|
+
throw new Error("Cannot load bridge state; refusing to discard history");
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
const existingLock = checkAgentLock({ lockDir, agentId: config.agentId });
|
|
110
|
+
if (existingLock.locked) {
|
|
111
|
+
throw new Error(
|
|
112
|
+
`Agent identity ${config.agentId} is already locked by live process ${existingLock.holder?.pid ?? "unknown"} (${existingLock.holder?.runtime ?? "unknown"})`,
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if (
|
|
116
|
+
!acquireAgentLock({
|
|
117
|
+
lockDir,
|
|
118
|
+
agentId: config.agentId,
|
|
119
|
+
runtime: "codex-bridge",
|
|
120
|
+
})
|
|
121
|
+
) {
|
|
122
|
+
throw new Error(`Cannot acquire agent lock for ${config.agentId}`);
|
|
123
|
+
}
|
|
124
|
+
} catch (err) {
|
|
125
|
+
try { unlinkSync(this.lock); } catch {}
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
69
128
|
}
|
|
70
129
|
private save() {
|
|
71
|
-
const
|
|
72
|
-
|
|
130
|
+
const isTerminal = (status: Entry["status"]) =>
|
|
131
|
+
status === "sent" || status === "skipped" || status === "blocked";
|
|
132
|
+
let terminalCount = 0;
|
|
133
|
+
for (const entry of this.state.entries) {
|
|
134
|
+
if (isTerminal(entry.status)) terminalCount++;
|
|
135
|
+
}
|
|
136
|
+
if (terminalCount > MAX_BRIDGE_TERMINAL_ENTRIES) {
|
|
137
|
+
let dropRemaining = terminalCount - MAX_BRIDGE_TERMINAL_ENTRIES;
|
|
138
|
+
this.state.entries = this.state.entries.filter((entry) => {
|
|
139
|
+
if (dropRemaining > 0 && isTerminal(entry.status)) {
|
|
140
|
+
dropRemaining--;
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
return true;
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
const tmp = `${this.file}.tmp.${process.pid}.${Date.now()}.${randomBytes(16).toString("hex")}`;
|
|
147
|
+
try {
|
|
148
|
+
const serialized = JSON.stringify(this.state);
|
|
149
|
+
checkStateDir(this.config.stateDir);
|
|
150
|
+
writeFileSync(tmp, serialized, { mode: 0o600, flag: "wx" });
|
|
151
|
+
atomicReplaceRegularFile(tmp, this.file, () => {
|
|
152
|
+
try {
|
|
153
|
+
const stat = lstatSync(this.file);
|
|
154
|
+
if (stat.isSymbolicLink() || !stat.isFile()) throw new Error("Bridge state must not be a symlink");
|
|
155
|
+
} catch (error: any) { if (error.code !== "ENOENT") throw error; }
|
|
156
|
+
checkStateDir(this.config.stateDir);
|
|
157
|
+
});
|
|
158
|
+
} catch (err) {
|
|
159
|
+
try { unlinkSync(tmp); } catch {}
|
|
160
|
+
throw err;
|
|
161
|
+
}
|
|
73
162
|
}
|
|
74
163
|
accept(raw: unknown): boolean {
|
|
75
164
|
if (this.stopped || !addressed(raw, this.config)) return false;
|
|
@@ -84,13 +173,15 @@ export class Bridge {
|
|
|
84
173
|
const message: ChatMessage = { id: raw.id, channel_id: raw.channel_id, sender_id: raw.sender_id,
|
|
85
174
|
...(Array.isArray(raw.mentioned_ids) ? { mentioned_ids: raw.mentioned_ids.filter((id: unknown) => typeof id === "string") } : {}),
|
|
86
175
|
...(Array.isArray(raw.mentions) ? { mentions: raw.mentions.filter((id: unknown) => typeof id === "string") } : {}),
|
|
176
|
+
...(!tick && typeof raw.parent_id === "string" && safeMessageId(raw.parent_id.trim()) ? { parent_id: raw.parent_id.trim() } : {}),
|
|
177
|
+
...(!tick && typeof raw.reply_to === "string" && safeMessageId(raw.reply_to.trim()) ? { reply_to: raw.reply_to.trim() } : {}),
|
|
87
178
|
content: tick ? "Authorized scheduled loop" : this.redact(raw.content),
|
|
88
179
|
...(tick ? { meta: { kind: "loop_tick", loop_id: tick.loop_id, interval_ms: tick.interval_ms,
|
|
89
180
|
next_tick_ms: tick.next_tick_ms, prompt: tick.prompt } as LoopTick } : {}) };
|
|
90
181
|
this.state.entries.push({ message, status: "pending" }); this.save();
|
|
91
182
|
void this.drain(); return true;
|
|
92
183
|
}
|
|
93
|
-
redact(text: string) { return redactSecrets(text.split(this.config.token).join("[REDACTED]")); }
|
|
184
|
+
redact(text: string) { return redactSecrets(this.config.token ? text.split(this.config.token).join("[REDACTED]") : text); }
|
|
94
185
|
/** History cursors may advance past ignored/known messages, never a full inbox. */
|
|
95
186
|
recover(raw: unknown): boolean {
|
|
96
187
|
if (this.stopped) return false;
|
|
@@ -108,8 +199,9 @@ export class Bridge {
|
|
|
108
199
|
}
|
|
109
200
|
/** Can be called while idle to migrate existing channels without sending messages. */
|
|
110
201
|
async prepareChannel(chat: string): Promise<ChannelThread> {
|
|
202
|
+
if (!safeMessageId(chat)) throw new Error("Invalid channel ID");
|
|
111
203
|
this.state.channels ??= {};
|
|
112
|
-
let channel = this.state.channels[chat];
|
|
204
|
+
let channel = Object.prototype.hasOwnProperty.call(this.state.channels, chat) ? this.state.channels[chat] : undefined;
|
|
113
205
|
if (!this.loaded.has(chat)) {
|
|
114
206
|
const namespace = this.codex.namespace;
|
|
115
207
|
if (channel?.namespace && channel.namespace !== namespace)
|
|
@@ -167,7 +259,7 @@ export class Bridge {
|
|
|
167
259
|
delete channel.bootstrap;
|
|
168
260
|
if (teamLead && e.answer.trim() === TEAM_LEAD_NO_UPDATE) {
|
|
169
261
|
e.status = "skipped"; delete e.answer; e.message.content = ""; this.save();
|
|
170
|
-
this.log(`Scheduled skill completed quietly in ${JSON.stringify(chat)}`);
|
|
262
|
+
this.log(cleanBridgeLog(`Scheduled skill completed quietly in ${JSON.stringify(chat)}`));
|
|
171
263
|
continue;
|
|
172
264
|
}
|
|
173
265
|
e.status = "ready"; this.save();
|
|
@@ -176,17 +268,20 @@ export class Bridge {
|
|
|
176
268
|
e.status = "sending"; this.save();
|
|
177
269
|
await this.send(e.message.channel_id, e.answer!);
|
|
178
270
|
e.status = "sent"; delete e.answer; e.message.content = ""; this.save();
|
|
179
|
-
this.log(`Replied in ${JSON.stringify(e.message.channel_id)}`);
|
|
271
|
+
this.log(cleanBridgeLog(`Replied in ${JSON.stringify(e.message.channel_id)}`));
|
|
180
272
|
} catch (error) {
|
|
181
273
|
if (error instanceof ThreadBusyError) {
|
|
182
274
|
e.status = "pending"; e.error = error.message; this.save();
|
|
183
275
|
this.log("Conversation in use; queued message will resume in the same task");
|
|
184
|
-
if (!this.stopped)
|
|
276
|
+
if (!this.stopped) {
|
|
277
|
+
this.retry = setTimeout(() => { this.retry = undefined; void this.drain(); }, 5000);
|
|
278
|
+
this.retry.unref?.();
|
|
279
|
+
}
|
|
185
280
|
return;
|
|
186
281
|
}
|
|
187
282
|
e.error = this.redact(error instanceof Error ? error.message : "Bridge operation failed").slice(0, 240);
|
|
188
283
|
e.status = e.status === "sending" ? "uncertain" : "failed";
|
|
189
|
-
this.save(); this.log(`Message ${JSON.stringify(e.message.id)} ${e.status}; inspect private state before retrying`);
|
|
284
|
+
this.save(); this.log(cleanBridgeLog(`Message ${JSON.stringify(e.message.id)} ${e.status}; inspect private state before retrying`));
|
|
190
285
|
} finally { this.activity(e.message.channel_id, false); }
|
|
191
286
|
}
|
|
192
287
|
}
|
|
@@ -194,7 +289,11 @@ export class Bridge {
|
|
|
194
289
|
async stop() {
|
|
195
290
|
this.pause();
|
|
196
291
|
await this.draining;
|
|
197
|
-
|
|
292
|
+
try {
|
|
293
|
+
const stat = lstatSync(this.lock);
|
|
294
|
+
if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024 &&
|
|
295
|
+
readFileSync(this.lock, "utf8") === String(process.pid)) unlinkSync(this.lock);
|
|
296
|
+
} catch (error: any) { if (error.code !== "ENOENT") throw error; }
|
|
198
297
|
const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
199
298
|
releaseAgentLock({ lockDir: resolveLockDir(homeDir, process.env), agentId: this.config.agentId });
|
|
200
299
|
}
|
package/codex/config.ts
CHANGED
|
@@ -1,22 +1,31 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { copyFileSync, lstatSync, readFileSync, realpathSync, renameSync, unlinkSync, type Stats } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { isAbsolute, join, resolve } from "node:path";
|
|
3
|
+
import { dirname, isAbsolute, join, parse as parsePath, resolve } from "node:path";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
import { validateIdentityProfile } from "../src/identity.ts";
|
|
6
6
|
import { parse as parseToml } from "smol-toml";
|
|
7
|
+
import { blockedServerHost } from "./owner.ts";
|
|
7
8
|
|
|
8
9
|
export type PermissionMode = "full-access" | "read-only";
|
|
9
10
|
// App Server advertises model-specific, nonempty effort names via model/list.
|
|
10
11
|
export type ReasoningEffort = string;
|
|
12
|
+
const CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
13
|
+
const PROTO_KEY_RE = /^(?:__proto__|constructor|prototype)$/i;
|
|
14
|
+
const RESERVED_OBJECT_STEMS = new Set([
|
|
15
|
+
"__proto__", "constructor", "prototype",
|
|
16
|
+
...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
|
|
17
|
+
]);
|
|
18
|
+
const WINDOWS_DEVICE_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
|
|
11
19
|
export function reasoningEffort(value: unknown): ReasoningEffort | undefined {
|
|
12
20
|
if (value === undefined) return undefined;
|
|
13
|
-
if (typeof value !== "string" || !value.trim())
|
|
21
|
+
if (typeof value !== "string" || !value.trim() || value.trim().length > 64 || CONTROL_CHAR_RE.test(value) || PROTO_KEY_RE.test(value.trim()))
|
|
14
22
|
throw new Error("effort must be a nonempty model-supported reasoning effort name");
|
|
15
23
|
return value.trim();
|
|
16
24
|
}
|
|
17
25
|
export function modelName(value: unknown): string | undefined {
|
|
18
26
|
if (value === undefined) return undefined;
|
|
19
|
-
if (typeof value !== "string" || !value.trim()
|
|
27
|
+
if (typeof value !== "string" || !value.trim() || value.trim().length > 256 || CONTROL_CHAR_RE.test(value) || PROTO_KEY_RE.test(value.trim()))
|
|
28
|
+
throw new Error("model must be a nonempty model ID");
|
|
20
29
|
return value.trim();
|
|
21
30
|
}
|
|
22
31
|
export function permissionMode(value: unknown): PermissionMode {
|
|
@@ -36,22 +45,119 @@ export interface BridgeConfig {
|
|
|
36
45
|
codexBin: string; stateDir: string; codexHomeMode?: CodexHomeMode; permissions: PermissionMode; effort?: ReasoningEffort; model?: string;
|
|
37
46
|
}
|
|
38
47
|
export interface IdentitySettings { state_root?: string; codex_home_mode?: CodexHomeMode; permissions?: PermissionMode; effort?: ReasoningEffort; model?: string; profile?: string; agent_id?: string; channels?: string[]; senders?: string[]; api_url?: string; ws_url?: string }
|
|
48
|
+
const MAX_CONFIG_BYTES = 1_048_576;
|
|
49
|
+
export function reservedProfileStem(selector: string): boolean {
|
|
50
|
+
const stem = selector.replace(/\.json$/i, "").toLowerCase();
|
|
51
|
+
return RESERVED_OBJECT_STEMS.has(stem) || WINDOWS_DEVICE_STEM_RE.test(stem) || [
|
|
52
|
+
"grok-binds", "session-binds", "agy-binds",
|
|
53
|
+
"cursor", "read-cursors", "wake-pids", "config", "codex-bots",
|
|
54
|
+
].includes(stem);
|
|
55
|
+
}
|
|
56
|
+
function checkSingleAncestorDir(path: string): void {
|
|
57
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
58
|
+
if (!stat) return;
|
|
59
|
+
if (stat.isSymbolicLink()) {
|
|
60
|
+
// These exact Darwin system aliases are safe; arbitrary user links are not.
|
|
61
|
+
const target = `/private${path}`;
|
|
62
|
+
if (process.platform === "darwin" && ["/var", "/tmp", "/etc"].includes(path) && realpathSync(path) === target) {
|
|
63
|
+
const priv = lstatSync("/private", { throwIfNoEntry: false });
|
|
64
|
+
if (!priv || priv.isSymbolicLink() || !priv.isDirectory()) {
|
|
65
|
+
throw new Error("Config path must be a non-symlink directory: /private");
|
|
66
|
+
}
|
|
67
|
+
assertDirectoryAncestors(target);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
throw new Error(`Config path must be a non-symlink directory: ${path}`);
|
|
71
|
+
}
|
|
72
|
+
if (!stat.isDirectory()) throw new Error(`Config path must be a non-symlink directory: ${path}`);
|
|
73
|
+
}
|
|
74
|
+
/** Inspect every existing directory before reads or recursive creation, including raw `symlink/..` segments. */
|
|
75
|
+
export function assertDirectoryAncestors(directory: string): void {
|
|
76
|
+
if (typeof directory !== "string" || !directory.trim() || CONTROL_CHAR_RE.test(directory)) {
|
|
77
|
+
throw new Error(`Config path must be a non-symlink directory: ${String(directory)}`);
|
|
78
|
+
}
|
|
79
|
+
if (/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(directory)) {
|
|
80
|
+
let cur: string;
|
|
81
|
+
let remainder: string;
|
|
82
|
+
if (isAbsolute(directory)) {
|
|
83
|
+
const root = parsePath(directory).root || "/";
|
|
84
|
+
cur = root;
|
|
85
|
+
remainder = directory.slice(root.length);
|
|
86
|
+
checkSingleAncestorDir(cur);
|
|
87
|
+
} else {
|
|
88
|
+
const base = resolve(process.cwd());
|
|
89
|
+
assertDirectoryAncestors(base);
|
|
90
|
+
cur = base;
|
|
91
|
+
remainder = directory;
|
|
92
|
+
}
|
|
93
|
+
for (const seg of remainder.split(/[\\/]+/)) {
|
|
94
|
+
if (!seg || seg === ".") continue;
|
|
95
|
+
cur = seg === ".." ? dirname(cur) : join(cur, seg);
|
|
96
|
+
checkSingleAncestorDir(cur);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const paths: string[] = [];
|
|
100
|
+
for (let path = resolve(directory);; path = dirname(path)) {
|
|
101
|
+
paths.unshift(path);
|
|
102
|
+
if (dirname(path) === path) break;
|
|
103
|
+
}
|
|
104
|
+
for (const path of paths) checkSingleAncestorDir(path);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Atomically replace a regular file, with Windows NTFS EPERM/EACCES fallback. */
|
|
108
|
+
export function atomicReplaceRegularFile(
|
|
109
|
+
tmp: string,
|
|
110
|
+
target: string,
|
|
111
|
+
verifySafeTarget: () => void,
|
|
112
|
+
opts?: { platform?: NodeJS.Platform; rename?: typeof renameSync },
|
|
113
|
+
): void {
|
|
114
|
+
verifySafeTarget();
|
|
115
|
+
const rename = opts?.rename ?? renameSync;
|
|
116
|
+
const platform = opts?.platform ?? process.platform;
|
|
117
|
+
try {
|
|
118
|
+
rename(tmp, target);
|
|
119
|
+
} catch (err: any) {
|
|
120
|
+
if (platform === "win32" && (err?.code === "EPERM" || err?.code === "EACCES")) {
|
|
121
|
+
verifySafeTarget();
|
|
122
|
+
copyFileSync(tmp, target);
|
|
123
|
+
unlinkSync(tmp);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
throw err;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function checkedPath(path: string, directory = false): Stats | undefined {
|
|
130
|
+
assertDirectoryAncestors(dirname(path));
|
|
131
|
+
let stat: Stats;
|
|
132
|
+
try { stat = lstatSync(path); }
|
|
133
|
+
catch (error: any) { if (error.code === "ENOENT") return undefined; throw error; }
|
|
134
|
+
if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()))
|
|
135
|
+
throw new Error(directory ? `Config directory must be a non-symlink directory: ${path}` : `Selected profile is not a regular file: ${path}`);
|
|
136
|
+
if (!directory && stat.size > MAX_CONFIG_BYTES) throw new Error(`Config file exceeds 1 MiB: ${path}`);
|
|
137
|
+
return stat;
|
|
138
|
+
}
|
|
39
139
|
function readJson(file: string): any {
|
|
40
|
-
|
|
140
|
+
let value: any;
|
|
141
|
+
try { value = JSON.parse(readFileSync(file, "utf8")); }
|
|
41
142
|
catch { throw new Error(`Cannot read valid JSON: ${file}`); }
|
|
143
|
+
if (value && typeof value === "object" && Object.hasOwn(value, "__proto__")) throw new Error("Invalid JSON prototype key");
|
|
144
|
+
return value;
|
|
42
145
|
}
|
|
43
146
|
function strings(value: unknown, name: string): string[] {
|
|
44
147
|
if (value === undefined) return [];
|
|
45
|
-
if (!Array.isArray(value) || value.some(x => typeof x !== "string" || !x.trim()))
|
|
148
|
+
if (!Array.isArray(value) || value.some(x => typeof x !== "string" || !x.trim() || CONTROL_CHAR_RE.test(x)))
|
|
46
149
|
throw new Error(`${name} must be an array of nonempty strings`);
|
|
47
150
|
return value;
|
|
48
151
|
}
|
|
49
152
|
export function resolveConfig(opts: { cwd?: string; profile?: string; codexBin?: string; stateRoot?: string; codexHomeMode?: string; settings?: IdentitySettings },
|
|
50
153
|
env: NodeJS.ProcessEnv = process.env, home = homedir()): BridgeConfig {
|
|
154
|
+
assertDirectoryAncestors(opts.cwd ?? process.cwd());
|
|
51
155
|
const cwd = realpathSync(opts.cwd ?? process.cwd());
|
|
52
156
|
const configFile = join(cwd, ".agentschat/config.json");
|
|
53
|
-
|
|
157
|
+
if (opts.settings === undefined) checkedPath(join(cwd, ".agentschat"), true);
|
|
158
|
+
const project = opts.settings ?? (checkedPath(configFile) ? readJson(configFile) : {});
|
|
54
159
|
if (!project || typeof project !== "object" || Array.isArray(project)) throw new Error("Invalid project config");
|
|
160
|
+
if (["__proto__", "constructor", "prototype"].some(key => Object.hasOwn(project, key))) throw new Error("Invalid project config prototype key");
|
|
55
161
|
const allowed = new Set(["profile", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "state_root", "codex_home_mode"]);
|
|
56
162
|
if (Object.keys(project).some(k => !allowed.has(k))) throw new Error("Unknown project config field (credentials belong in a private profile)");
|
|
57
163
|
for (const k of ["profile", "agent_id", "api_url", "ws_url", "state_root"])
|
|
@@ -61,7 +167,8 @@ export function resolveConfig(opts: { cwd?: string; profile?: string; codexBin?:
|
|
|
61
167
|
// must not execute the configured MCP command or inherit its token overrides.
|
|
62
168
|
let codexProfile: string | undefined;
|
|
63
169
|
const codexFile = join(cwd, ".codex/config.toml");
|
|
64
|
-
if (opts.settings === undefined
|
|
170
|
+
if (opts.settings === undefined) checkedPath(join(cwd, ".codex"), true);
|
|
171
|
+
if (opts.settings === undefined && checkedPath(codexFile)) {
|
|
65
172
|
let doc: any;
|
|
66
173
|
try { doc = parseToml(readFileSync(codexFile, "utf8")); }
|
|
67
174
|
catch { throw new Error("Invalid project .codex/config.toml"); }
|
|
@@ -76,22 +183,29 @@ export function resolveConfig(opts: { cwd?: string; profile?: string; codexBin?:
|
|
|
76
183
|
}
|
|
77
184
|
const choices = [
|
|
78
185
|
[opts.profile, "flag"], [project.profile, "project-config"],
|
|
79
|
-
[opts.settings === undefined &&
|
|
186
|
+
[opts.settings === undefined && checkedPath(localProfile) ? localProfile : undefined, "project-profile"],
|
|
80
187
|
[codexProfile, "project-codex"],
|
|
81
188
|
[env.AGENTSCHAT_PROFILE, "env"], [env.AGENTCHAT_PROFILE, "legacy-env"], ["profile", "default"],
|
|
82
189
|
];
|
|
83
190
|
const [selector, source] = choices.find(([v]) => v !== undefined && v !== "") as [string, string];
|
|
191
|
+
if (typeof selector !== "string" || CONTROL_CHAR_RE.test(selector)) throw new Error("Invalid profile selector");
|
|
84
192
|
let profileFile: string;
|
|
85
|
-
if (selector
|
|
86
|
-
else if (isAbsolute(selector) || selector.includes("/")) profileFile = resolve(cwd, selector);
|
|
193
|
+
if (/^~[\\/]/.test(selector)) profileFile = join(home, selector.slice(2));
|
|
194
|
+
else if (isAbsolute(selector) || selector.includes("/") || selector.includes("\\")) profileFile = resolve(cwd, selector);
|
|
87
195
|
else {
|
|
88
|
-
const
|
|
196
|
+
const stem = selector.replace(/\.json$/i, "");
|
|
197
|
+
if (!stem || selector.includes("..") || reservedProfileStem(selector)) {
|
|
198
|
+
throw new Error("Invalid central profile selector");
|
|
199
|
+
}
|
|
200
|
+
const name = /\.json$/i.test(selector) ? selector : `${selector}.json`;
|
|
89
201
|
profileFile = join(home, ".agentschat/profiles", name);
|
|
90
|
-
if (!
|
|
91
|
-
if (!
|
|
202
|
+
if (!checkedPath(profileFile)) profileFile = join(home, ".agentschat", name);
|
|
203
|
+
if (!checkedPath(profileFile)) profileFile = join(home, ".agentchat", name);
|
|
92
204
|
}
|
|
93
|
-
if (!
|
|
94
|
-
|
|
205
|
+
if (!checkedPath(profileFile)) throw new Error(`Selected profile missing: ${profileFile}; no identity fallback or registration`);
|
|
206
|
+
const profileStat = checkedPath(profileFile)!;
|
|
207
|
+
if (!profileStat.isFile()) throw new Error(`Selected profile is not a regular file: ${profileFile}`);
|
|
208
|
+
if (process.platform !== "win32" && (profileStat.mode & 0o077)) throw new Error(`Profile must be private (chmod 600): ${profileFile}`);
|
|
95
209
|
const profile = readJson(profileFile);
|
|
96
210
|
validateIdentityProfile(profile, profileFile);
|
|
97
211
|
if (project.agent_id !== undefined && project.agent_id !== profile.agent_id) throw new Error("Project agent_id does not match selected profile");
|
|
@@ -99,16 +213,18 @@ export function resolveConfig(opts: { cwd?: string; profile?: string; codexBin?:
|
|
|
99
213
|
const wsUrl = project.ws_url ?? `${apiUrl.replace(/^http/, "ws").replace(/\/$/, "")}/ws`;
|
|
100
214
|
for (const [raw, protocols] of [[apiUrl, ["https:", "http:"]], [wsUrl, ["wss:", "ws:"]]] as const) {
|
|
101
215
|
const url = new URL(raw);
|
|
102
|
-
if (!(protocols as readonly string[]).includes(url.protocol) || url.username || url.password || url.search || url.hash ||
|
|
103
|
-
(!url.protocol.endsWith("s:") && !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) throw new Error("Server URLs must use TLS (except loopback) and contain no credentials/query");
|
|
216
|
+
if (blockedServerHost(url) || !(protocols as readonly string[]).includes(url.protocol) || url.username || url.password || url.search || url.hash || url.port === "0" ||
|
|
217
|
+
(!url.protocol.endsWith("s:") && !["127.0.0.1", "localhost", "[::1]", "::1"].includes(url.hostname.toLowerCase().replace(/\.$/, "")))) throw new Error("Server URLs must use TLS (except loopback) and contain no credentials/query");
|
|
104
218
|
}
|
|
105
219
|
const canonicalApi = new URL(apiUrl).href.replace(/\/$/, "");
|
|
106
220
|
const key = createHash("sha256").update(JSON.stringify([cwd, canonicalApi, profile.agent_id])).digest("hex").slice(0, 24);
|
|
107
221
|
const root = opts.stateRoot ?? project.state_root;
|
|
108
|
-
if (root !== undefined && (typeof root !== "string" || !root.trim())) throw new Error("Invalid state_root");
|
|
109
|
-
const
|
|
222
|
+
if (root !== undefined && (typeof root !== "string" || !root.trim() || CONTROL_CHAR_RE.test(root))) throw new Error("Invalid state_root");
|
|
223
|
+
const codexBin = opts.codexBin ?? "codex";
|
|
224
|
+
if (typeof codexBin !== "string" || !codexBin.trim() || CONTROL_CHAR_RE.test(codexBin)) throw new Error("Invalid codex_bin");
|
|
225
|
+
const stateRoot = root === undefined ? join(home, ".agentschat/codex-bridge") : /^~[\\/]/.test(root) ? join(home, root.slice(2)) : resolve(cwd, root);
|
|
110
226
|
return { cwd, profileFile, source, codexHomeMode: codexHomeMode(opts.codexHomeMode ?? project.codex_home_mode), permissions: permissionMode(project.permissions), effort: reasoningEffort(project.effort), model: modelName(project.model), agentId: profile.agent_id, token: profile.token,
|
|
111
227
|
apiUrl: canonicalApi, wsUrl, channels: strings(project.channels, "channels"),
|
|
112
|
-
senders: strings(project.senders, "senders"), codexBin
|
|
228
|
+
senders: strings(project.senders, "senders"), codexBin,
|
|
113
229
|
stateDir: join(stateRoot, key) };
|
|
114
230
|
}
|
package/codex/gui-channel.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { assertDirectoryAncestors, atomicReplaceRegularFile } from "./config.ts";
|
|
1
2
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { mkdirSync, writeFileSync, readFileSync,
|
|
3
|
+
import { mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, lstatSync } from "node:fs";
|
|
3
4
|
import { join } from "node:path";
|
|
4
5
|
|
|
5
6
|
export type GuiTool = "send_message_to_thread" | "read_thread";
|
|
@@ -15,14 +16,28 @@ function payload(result: any): any {
|
|
|
15
16
|
if (Array.isArray(result?.content)) {
|
|
16
17
|
const text = result.content.find((c: any) => c.type === "text")?.text;
|
|
17
18
|
if (!text) throw new Error("GUI tool returned no receipt");
|
|
18
|
-
|
|
19
|
+
if (typeof text !== "string" || text.length > 1_048_576) throw new Error("GUI receipt exceeds size limit");
|
|
20
|
+
const parsed = JSON.parse(text);
|
|
21
|
+
if (parsed && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) throw new Error("Invalid GUI receipt");
|
|
22
|
+
return parsed;
|
|
19
23
|
}
|
|
20
24
|
return result;
|
|
21
25
|
}
|
|
26
|
+
function validTarget(value: unknown): value is string {
|
|
27
|
+
return typeof value === "string" && value.trim() === value && value.length >= 1 && value.length <= 256 && value !== "." && value !== ".." &&
|
|
28
|
+
!/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) &&
|
|
29
|
+
!/%(?:2e%2e|2f|5c|00)|%25(?:2e|2f|5c|00)/i.test(value) &&
|
|
30
|
+
!["__proto__", "prototype", "constructor"].includes(value.toLowerCase());
|
|
31
|
+
}
|
|
22
32
|
/** Private durable outbox. An authorized GUI host calls dispatch; enqueue is NOT delivery. */
|
|
23
33
|
export class GuiChannel {
|
|
24
34
|
constructor(private directory: string, private allowedThreads: readonly string[]) {
|
|
35
|
+
const existing = lstatSync(directory, { throwIfNoEntry: false });
|
|
36
|
+
if (existing && (existing.isSymbolicLink() || !existing.isDirectory())) throw new Error("GUI outbox must be a real directory, not a symlink");
|
|
37
|
+
assertDirectoryAncestors(directory);
|
|
25
38
|
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
39
|
+
const stat = lstatSync(directory);
|
|
40
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("GUI outbox must be a real directory, not a symlink");
|
|
26
41
|
}
|
|
27
42
|
private path(id: string) {
|
|
28
43
|
if (!/^[0-9a-f-]{36}$/.test(id)) throw new Error("Invalid delivery ID");
|
|
@@ -30,13 +45,44 @@ export class GuiChannel {
|
|
|
30
45
|
}
|
|
31
46
|
private save(entry: GuiDelivery) {
|
|
32
47
|
const path = this.path(entry.id), temp = `${path}.${randomUUID()}.tmp`;
|
|
33
|
-
|
|
48
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
49
|
+
if (stat?.isSymbolicLink() || (stat && !stat.isFile())) throw new Error("GUI receipt must be a regular file, not a symlink");
|
|
50
|
+
try {
|
|
51
|
+
writeFileSync(temp, JSON.stringify(entry), { mode: 0o600, flag: "wx" });
|
|
52
|
+
atomicReplaceRegularFile(temp, path, () => {
|
|
53
|
+
const current = lstatSync(path, { throwIfNoEntry: false });
|
|
54
|
+
if (current && (current.isSymbolicLink() || !current.isFile())) throw new Error("GUI receipt must be a regular file, not a symlink");
|
|
55
|
+
});
|
|
56
|
+
} catch (error) {
|
|
57
|
+
// An exclusive-create collision belongs to another writer; leave it alone.
|
|
58
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") rmSync(temp, { force: true });
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
get(id: string): GuiDelivery {
|
|
63
|
+
const path = this.path(id), stat = lstatSync(path);
|
|
64
|
+
if (stat.isSymbolicLink() || !stat.isFile()) throw new Error("GUI receipt must be a regular file, not a symlink");
|
|
65
|
+
if (stat.size > 1_048_576) throw new Error("GUI receipt exceeds size limit");
|
|
66
|
+
const entry = JSON.parse(readFileSync(path, "utf8"));
|
|
67
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.prototype.hasOwnProperty.call(entry, "__proto__") || entry.id !== id ||
|
|
68
|
+
!validTarget(entry.threadId) || typeof entry.prompt !== "string" ||
|
|
69
|
+
typeof entry.createdAt !== "string" ||
|
|
70
|
+
!["pending", "sending", "submitted", "delivered", "uncertain"].includes(entry.status) ||
|
|
71
|
+
(entry.hostId !== undefined && !validTarget(entry.hostId)) ||
|
|
72
|
+
(entry.turnId !== undefined && typeof entry.turnId !== "string") ||
|
|
73
|
+
(entry.deliveredAt !== undefined && typeof entry.deliveredAt !== "string")) throw new Error("Invalid GUI receipt");
|
|
74
|
+
return entry;
|
|
34
75
|
}
|
|
35
|
-
get(id: string): GuiDelivery { return JSON.parse(readFileSync(this.path(id), "utf8")); }
|
|
36
76
|
list(): GuiDelivery[] {
|
|
37
|
-
|
|
77
|
+
const entries: GuiDelivery[] = [];
|
|
78
|
+
for (const file of readdirSync(this.directory)) {
|
|
79
|
+
if (!/^[0-9a-f-]{36}\.json$/.test(file)) continue;
|
|
80
|
+
try { entries.push(this.get(file.slice(0, -5))); } catch { /* Isolate damaged or unsafe receipts. */ }
|
|
81
|
+
}
|
|
82
|
+
return entries;
|
|
38
83
|
}
|
|
39
84
|
enqueue(threadId: string, text: string, hostId?: string): GuiDelivery {
|
|
85
|
+
if (!validTarget(threadId) || (hostId !== undefined && !validTarget(hostId))) throw new Error("Invalid GUI target");
|
|
40
86
|
if (!this.allowedThreads.includes(threadId)) throw new Error("GUI target is not allowed");
|
|
41
87
|
if (!text.trim() || text.length > 24000) throw new Error("GUI message must contain 1–24000 characters");
|
|
42
88
|
const id = randomUUID();
|
|
@@ -46,7 +92,16 @@ export class GuiChannel {
|
|
|
46
92
|
}
|
|
47
93
|
async dispatch(id: string, call: GuiToolCaller): Promise<GuiDelivery> {
|
|
48
94
|
const lock = `${this.path(id)}.lock`;
|
|
49
|
-
mkdirSync(lock, { mode: 0o700 });
|
|
95
|
+
try { mkdirSync(lock, { mode: 0o700 }); }
|
|
96
|
+
catch (error) {
|
|
97
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
98
|
+
const stat = lstatSync(lock);
|
|
99
|
+
if (stat.isSymbolicLink()) throw new Error("GUI delivery lock must not be a symlink");
|
|
100
|
+
const ageMs = Date.now() - stat.mtimeMs;
|
|
101
|
+
if (!stat.isDirectory() || (ageMs >= -5 * 60_000 && ageMs <= 5 * 60_000)) throw error;
|
|
102
|
+
rmSync(lock, { recursive: true, force: true });
|
|
103
|
+
mkdirSync(lock, { mode: 0o700 });
|
|
104
|
+
}
|
|
50
105
|
try {
|
|
51
106
|
const entry = this.get(id);
|
|
52
107
|
if (!this.allowedThreads.includes(entry.threadId)) throw new Error("GUI target is no longer allowed");
|
|
@@ -65,6 +120,7 @@ export class GuiChannel {
|
|
|
65
120
|
if (entry.status === "sending") { entry.status = "uncertain"; this.save(entry); }
|
|
66
121
|
try {
|
|
67
122
|
let cursor: string | undefined;
|
|
123
|
+
const seenCursors = new Set<string>();
|
|
68
124
|
for (let page = 0; page < 5; page++) {
|
|
69
125
|
const history = payload(await call("read_thread", {...target, turnLimit: 10,
|
|
70
126
|
maxOutputCharsPerItem: 32000, ...(cursor ? {cursor} : {})}));
|
|
@@ -75,11 +131,12 @@ export class GuiChannel {
|
|
|
75
131
|
entry.status = "delivered"; entry.deliveredAt = new Date().toISOString(); entry.turnId = turn.id;
|
|
76
132
|
this.save(entry); break;
|
|
77
133
|
}
|
|
78
|
-
|
|
79
|
-
if (!
|
|
134
|
+
const nextCursor = history.page?.nextCursor;
|
|
135
|
+
if (typeof nextCursor !== "string" || !nextCursor.length || seenCursors.has(nextCursor)) break;
|
|
136
|
+
seenCursors.add(nextCursor); cursor = nextCursor;
|
|
80
137
|
}
|
|
81
138
|
} catch { /* Keep submitted/uncertain; an unavailable read is not proof of failure. */ }
|
|
82
139
|
return entry;
|
|
83
|
-
} finally { rmSync(lock, {recursive: true}); }
|
|
140
|
+
} finally { rmSync(lock, {recursive: true, force: true}); }
|
|
84
141
|
}
|
|
85
142
|
}
|