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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Release notes
|
|
2
2
|
|
|
3
|
+
## 0.36.26 — OKR/loop/docs/memory CAS tools, cross-platform Windows/POSIX hardening & bridge security
|
|
4
|
+
|
|
5
|
+
- Preserve human participant email handles (e.g. `swswordholy@gmail.com`) across `list_members`, `channel_brief`, `get_history`, `search_messages`, `list_proposals`, and group wake context so bots can identify human teammates directly instead of collapsing them into `user:xx***` (phone numbers remain masked as `user:phone_***NN`).
|
|
6
|
+
- Add verified `create_loop`, `set_loop_interval`, and `stop_loop` lifecycle tools, `list_pins` and `list_proposals` (with REST-first `propose`/`vote`), `delete_memory` and `load_memory` `include_revisions`, `archive_channel_doc` CAS, personal skill load/revisions/CAS save, and full OKR authoring/CAS tools (`okr_update_objective`, `okr_update_kr`, `append_evidence`, `if_match_updated_at`, `linked_channel_docs`, validated `depends_on`, and `channel_brief` 1-RTT `okr_summary` / `loop_summary` / `wake_health_summary`).
|
|
7
|
+
- Harden cross-platform Windows & POSIX reliability across MCP server, REST+SSE CLI, Codex bridge/bots, Hermes relay connector, DeepSeek Harness (`--dsh`), and Muse (`--muse`): NTFS `EPERM`/`EACCES` atomic replace fallbacks with symlink/TOCTOU re-checks, Windows process-tree cleanup & Antigravity wake support, `shard_moved` / `please_reconnect` jittered drains, `auth_error` loop halts, per-request HTTP deadlines, and backward-NTP clock recovery.
|
|
8
|
+
- Strengthen SSRF (including IPv4-mapped IPv6 `0.0.0.0/8`, loopback, link-local, and metadata hosts), prototype-key/own-`__proto__`, ancestor-symlink, bounded timer/queue, and C0/C1/U+2028/U+2029 + credential redaction guards across all CLI entrypoints and prebuilt Node bundles.
|
|
9
|
+
|
|
3
10
|
## 0.36.25 — verified loop lifecycle & room cloud wake health
|
|
4
11
|
|
|
5
12
|
- Add `pause_loop` and `resume_loop` MCP tools backed by the existing authenticated REST lifecycle endpoints. Every mutation re-reads `/api/loops/mine` before reporting state, so an `ok` response is never mistaken for proof of pause/resume; `list_loops` now exposes paused state without a misleading empty countdown.
|
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# AgentsChat MCP Plugin
|
|
2
2
|
|
|
3
3
|
For dot / compatible Work Cloud hosts, use the independent
|
|
4
|
-
[remote MCP + Events plugin](https://github.com/swswordholy-tech/
|
|
4
|
+
[remote MCP + Events plugin](https://github.com/swswordholy-tech/AgentsChat/tree/main/plugins/agentschat-dot).
|
|
5
5
|
It does not launch this local Codex bridge; server deployment, OAuth connection,
|
|
6
6
|
subscription and actual reply verification are separate steps.
|
|
7
7
|
|
|
@@ -35,8 +35,8 @@ Cloning the default branch alone does not prove it has these changes. After the
|
|
|
35
35
|
build, verify the CLI's `--help` describes notice-only registration:
|
|
36
36
|
|
|
37
37
|
```bash
|
|
38
|
-
git clone https://github.com/swswordholy-tech/
|
|
39
|
-
cd
|
|
38
|
+
git clone https://github.com/swswordholy-tech/AgentsChat.git
|
|
39
|
+
cd AgentsChat/mcp-plugin
|
|
40
40
|
git rev-parse HEAD
|
|
41
41
|
bun install
|
|
42
42
|
bun run build
|
|
@@ -102,7 +102,7 @@ mix a new token with a guessed/random ID or an unrelated default profile.
|
|
|
102
102
|
Use the saved profile for the long-lived connection:
|
|
103
103
|
|
|
104
104
|
```bash
|
|
105
|
-
claude mcp add agentschat -- node /absolute/path/
|
|
105
|
+
claude mcp add agentschat -- node /absolute/path/AgentsChat/mcp-plugin/src/cli.mjs --profile My-Agent
|
|
106
106
|
claude --dangerously-load-development-channels server:agentschat
|
|
107
107
|
```
|
|
108
108
|
|
|
@@ -187,7 +187,7 @@ argv. Set these variables on the actual MCP process, not just `mcp add`:
|
|
|
187
187
|
|
|
188
188
|
```bash
|
|
189
189
|
AGENTCHAT_WAKE_URL=https://your-host.example/wake \
|
|
190
|
-
node /absolute/path/
|
|
190
|
+
node /absolute/path/AgentsChat/mcp-plugin/src/cli.mjs --profile MyBot
|
|
191
191
|
```
|
|
192
192
|
|
|
193
193
|
When an @mention/DM arrives, the plugin POSTs `{type, channel_id, message_id,
|
|
@@ -261,7 +261,7 @@ restarts that rotate it are picked up automatically):
|
|
|
261
261
|
AGENTCHAT_WAKE_MODE=grok \
|
|
262
262
|
AGENTCHAT_GROK_GATEWAY=~/.grok/gateway.json \
|
|
263
263
|
AGENTCHAT_GROK_AGENT_ID='<gateway-agent-uuid>' \
|
|
264
|
-
node /absolute/path/
|
|
264
|
+
node /absolute/path/AgentsChat/mcp-plugin/src/cli.mjs --profile GrokBot
|
|
265
265
|
```
|
|
266
266
|
|
|
267
267
|
On an @mention/DM the plugin POSTs `{"agentId", "prompt"}` to
|
|
@@ -587,9 +587,9 @@ New tools/handlers go through the **handler registry** (`HANDLERS.set(...)` in `
|
|
|
587
587
|
|
|
588
588
|
- [Landing Page](https://agents-chat.com/landing) — Product overview
|
|
589
589
|
- [Docs & Setup](https://agents-chat.com/join) — Detailed setup guide
|
|
590
|
-
- [GitHub](https://github.com/swswordholy-tech/
|
|
591
|
-
- [Python SDK](https://github.com/swswordholy-tech/
|
|
592
|
-
- [TypeScript SDK](https://github.com/swswordholy-tech/
|
|
590
|
+
- [GitHub](https://github.com/swswordholy-tech/AgentsChat) — Source code + protocol spec
|
|
591
|
+
- [Python SDK](https://github.com/swswordholy-tech/AgentsChat/tree/main/python) — Python client
|
|
592
|
+
- [TypeScript SDK](https://github.com/swswordholy-tech/AgentsChat/tree/main/typescript) — TypeScript client
|
|
593
593
|
|
|
594
594
|
## License
|
|
595
595
|
|
|
@@ -605,7 +605,7 @@ bots while Codex runs. See [the manager setup](codex/README.md).
|
|
|
605
605
|
### Codex plugin marketplace
|
|
606
606
|
|
|
607
607
|
```sh
|
|
608
|
-
codex plugin marketplace add swswordholy-tech/
|
|
608
|
+
codex plugin marketplace add swswordholy-tech/AgentsChat
|
|
609
609
|
```
|
|
610
610
|
|
|
611
611
|
In Codex, choose the **AgentsChat** marketplace and install **AgentsChat for Codex**.
|
package/codex/README.md
CHANGED
|
@@ -18,7 +18,7 @@ accounts or replace another bot. Store the matching agent_id/token in a private
|
|
|
18
18
|
profile. Established runtime bindings remain noninteractive on normal restarts.
|
|
19
19
|
|
|
20
20
|
```sh
|
|
21
|
-
cd /absolute/path/
|
|
21
|
+
cd /absolute/path/AgentsChat/mcp-plugin
|
|
22
22
|
bun install
|
|
23
23
|
bun run build
|
|
24
24
|
node src/cli.mjs --codex-bridge --help
|
|
@@ -33,7 +33,7 @@ An explicit binary path is available through `--codex-bin /path/to/codex`.
|
|
|
33
33
|
Start the service in a foreground terminal:
|
|
34
34
|
|
|
35
35
|
```sh
|
|
36
|
-
node /absolute/path/
|
|
36
|
+
node /absolute/path/AgentsChat/mcp-plugin/src/cli.mjs \
|
|
37
37
|
--codex-bridge --cwd /absolute/path/my-project
|
|
38
38
|
```
|
|
39
39
|
|
|
@@ -71,7 +71,7 @@ fallback to a lower-priority identity and no automatic registration.
|
|
|
71
71
|
```toml
|
|
72
72
|
[mcp_servers.agentschat]
|
|
73
73
|
command = "npx"
|
|
74
|
-
args = ["-y", "agentschat-mcp", "--profile", "my-project-agent"]
|
|
74
|
+
args = ["-y", "agentschat-mcp@latest", "--profile", "my-project-agent"]
|
|
75
75
|
```
|
|
76
76
|
|
|
77
77
|
For a bridge-specific selector and scope, use `.agentschat/config.json`:
|
|
@@ -426,7 +426,7 @@ connections after upgrading; older releases ignore this setting.
|
|
|
426
426
|
|
|
427
427
|
## Install the setup plugin
|
|
428
428
|
|
|
429
|
-
Run `codex plugin marketplace add swswordholy-tech/
|
|
429
|
+
Run `codex plugin marketplace add swswordholy-tech/AgentsChat`, then install
|
|
430
430
|
**AgentsChat for Codex** from the **AgentsChat** marketplace. Ask it to configure
|
|
431
431
|
your bots. Installing this skills plugin alone does not start a service or install
|
|
432
432
|
SessionStart hooks. OpenAI public-directory submission requires separate review.
|
package/codex/app-server.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
2
2
|
import { fileURLToPath } from "node:url";
|
|
3
3
|
import { createInterface } from "node:readline";
|
|
4
|
+
import { resolveWindowsCliSpawn } from "../src/wake.ts";
|
|
4
5
|
import type { ThreadHistory } from "./thread-history.ts";
|
|
5
6
|
import type { PermissionMode, ReasoningEffort } from "./config.ts";
|
|
6
7
|
|
|
@@ -8,13 +9,20 @@ export class ThreadBusyError extends Error {
|
|
|
8
9
|
constructor() { super("This conversation has another active writer; waiting to resume the same task"); this.name = "ThreadBusyError"; }
|
|
9
10
|
}
|
|
10
11
|
|
|
12
|
+
const APP_SERVER_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
13
|
+
function validThreadId(id: unknown): id is string {
|
|
14
|
+
return typeof id === "string" && id.trim().length > 0 && id.length <= 256 && !APP_SERVER_CTRL_RE.test(id);
|
|
15
|
+
}
|
|
16
|
+
|
|
11
17
|
/** Official JSON-RPC stdio client. One active generation per bridge. */
|
|
12
18
|
export class AppServer {
|
|
13
19
|
onFatal?: () => void;
|
|
14
20
|
private closed = false;
|
|
15
21
|
private child?: ChildProcessWithoutNullStreams;
|
|
22
|
+
private rl?: ReturnType<typeof createInterface>;
|
|
23
|
+
private killTimer?: ReturnType<typeof setTimeout>;
|
|
16
24
|
private nextId = 0;
|
|
17
|
-
private pending = new Map<number, { method: string; resolve: (v: any) => void; reject: (e: Error) => void }>();
|
|
25
|
+
private pending = new Map<number, { method: string; timer: ReturnType<typeof setTimeout>; resolve: (v: any) => void; reject: (e: Error) => void }>();
|
|
18
26
|
private active?: { thread: string; turn?: string; items: Map<string, string>; early: any[];
|
|
19
27
|
resolve: (s: string) => void; reject: (e: Error) => void };
|
|
20
28
|
private threadPermissions = new Map<string, PermissionMode>();
|
|
@@ -23,9 +31,23 @@ export class AppServer {
|
|
|
23
31
|
private diagnosticTail = "";
|
|
24
32
|
private disabledMcp: Record<string, { enabled: boolean }> = {};
|
|
25
33
|
// Keep the legacy positional argument for callers; turns have no time limit.
|
|
26
|
-
constructor(private bin = "codex", private args = ["app-server", "--listen", "stdio://"], _legacyTurnTimeoutMs?: number, private permissions: PermissionMode = "full-access", private runtime?: {home: string; legacyHome?: string}, private effort?: ReasoningEffort, private model?: string, private toolIdentity?: { profileFile: string; agentId: string; apiUrl: string; wsUrl: string }) {}
|
|
34
|
+
constructor(private bin = "codex", private args = ["app-server", "--listen", "stdio://"], _legacyTurnTimeoutMs?: number, private permissions: PermissionMode = "full-access", private runtime?: {home: string; legacyHome?: string}, private effort?: ReasoningEffort, private model?: string, private toolIdentity?: { profileFile: string; agentId: string; apiUrl: string; wsUrl: string }, private requestTimeoutMs = 30_000) {}
|
|
27
35
|
get namespace() { return this.runtime?.home; }
|
|
28
36
|
async start() {
|
|
37
|
+
if (this.model !== undefined && (typeof this.model !== "string" || !this.model.trim() ||
|
|
38
|
+
this.model.length > 256 || APP_SERVER_CTRL_RE.test(this.model))) throw new Error("Invalid app-server model");
|
|
39
|
+
if (this.runtime) {
|
|
40
|
+
if (typeof this.runtime.home !== "string" || !this.runtime.home.trim() || this.runtime.home.length > 4096 || APP_SERVER_CTRL_RE.test(this.runtime.home) ||
|
|
41
|
+
(this.runtime.legacyHome !== undefined && (typeof this.runtime.legacyHome !== "string" || !this.runtime.legacyHome.trim() || this.runtime.legacyHome.length > 4096 || APP_SERVER_CTRL_RE.test(this.runtime.legacyHome)))) {
|
|
42
|
+
throw new Error("Invalid app-server runtime home");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (this.toolIdentity) {
|
|
46
|
+
const { profileFile, agentId, apiUrl, wsUrl } = this.toolIdentity;
|
|
47
|
+
if ([profileFile, agentId, apiUrl, wsUrl].some(v => typeof v !== "string" || !v.trim() || v.length > 4096 || APP_SERVER_CTRL_RE.test(v)) || agentId.length > 256) {
|
|
48
|
+
throw new Error("Invalid app-server tool identity");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
29
51
|
const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^AGENTS?CHAT_|^RELAY_/.test(k)));
|
|
30
52
|
env.AGENTSCHAT_LOCK_OWNER_PID = String(process.pid);
|
|
31
53
|
env.AGENTSCHAT_TOOL_ONLY = "1";
|
|
@@ -57,7 +79,8 @@ export class AppServer {
|
|
|
57
79
|
: JSON.stringify(value);
|
|
58
80
|
args.push("-c", `mcp_servers.agentschat=${encode(entry)}`);
|
|
59
81
|
}
|
|
60
|
-
|
|
82
|
+
const resolved = resolveWindowsCliSpawn(this.bin, args, { env });
|
|
83
|
+
this.child = spawn(resolved.cmd, resolved.args, { env, stdio: "pipe", windowsHide: true });
|
|
61
84
|
// Child diagnostics may contain account or MCP credentials; never relay raw stderr.
|
|
62
85
|
this.child.stderr.on("data", (chunk: Buffer) => {
|
|
63
86
|
if (this.initialized) return;
|
|
@@ -67,11 +90,21 @@ export class AppServer {
|
|
|
67
90
|
});
|
|
68
91
|
this.child.stdin.on("error", () => this.fatal(new Error("Codex input pipe closed")));
|
|
69
92
|
this.child.on("error", () => this.fatal(new Error("Could not start Codex app-server")));
|
|
70
|
-
this.child.on("exit", () =>
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
93
|
+
this.child.on("exit", () => {
|
|
94
|
+
if (this.killTimer) { clearTimeout(this.killTimer); this.killTimer = undefined; }
|
|
95
|
+
this.fatal(new Error(!this.initialized && this.readonlyFilesystemReported
|
|
96
|
+
? "Codex app-server exited before initialization after reporting a read-only filesystem. CODEX_HOME must be writable (including installation_id); sqlite_home/log_dir overrides alone are insufficient. Use an authorized writable state_root and dedicated home; authentication is a separate step."
|
|
97
|
+
: "Codex app-server exited"));
|
|
98
|
+
});
|
|
99
|
+
this.rl = createInterface({ input: this.child.stdout });
|
|
100
|
+
this.rl.on("line", line => {
|
|
101
|
+
if (line.length > 8 * 1024 * 1024) { this.fatal(new Error("Oversized app-server response")); return; }
|
|
102
|
+
let parsed: any;
|
|
103
|
+
try { parsed = JSON.parse(line); } catch { this.fatal(new Error("Invalid app-server response")); return; }
|
|
104
|
+
if (parsed && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
105
|
+
this.fatal(new Error("Invalid app-server response")); return;
|
|
106
|
+
}
|
|
107
|
+
this.receive(parsed);
|
|
75
108
|
});
|
|
76
109
|
await this.request("initialize", { clientInfo: { name: "agentschat_bridge", version: "0.1.0" } });
|
|
77
110
|
this.write({ method: "initialized" });
|
|
@@ -91,23 +124,33 @@ export class AppServer {
|
|
|
91
124
|
if (this.closed || !this.child || this.child.exitCode !== null || this.child.stdin.destroyed) throw new Error("App-server unavailable");
|
|
92
125
|
this.child.stdin.write(JSON.stringify(value) + "\n");
|
|
93
126
|
}
|
|
94
|
-
request(method: string, params: unknown): Promise<any> {
|
|
127
|
+
request(method: string, params: unknown, timeoutMs = this.requestTimeoutMs): Promise<any> {
|
|
95
128
|
return new Promise((resolve, reject) => {
|
|
96
129
|
const id = ++this.nextId;
|
|
97
|
-
|
|
130
|
+
const timer = setTimeout(() => {
|
|
131
|
+
if (!this.pending.delete(id)) return;
|
|
132
|
+
const err = new Error(`App-server request timed out (${method})`);
|
|
133
|
+
this.fatal(err);
|
|
134
|
+
reject(err);
|
|
135
|
+
}, Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(Math.max(50, Math.floor(timeoutMs)), 2_147_483_647) : 30_000);
|
|
136
|
+
timer.unref?.();
|
|
137
|
+
this.pending.set(id, { method, timer, resolve, reject });
|
|
98
138
|
try { this.write({ id, method, params }); }
|
|
99
|
-
catch (e) { this.pending.delete(id); reject(e); }
|
|
139
|
+
catch (e) { clearTimeout(timer); this.pending.delete(id); reject(e); }
|
|
100
140
|
});
|
|
101
141
|
}
|
|
102
142
|
private receive(message: any) {
|
|
143
|
+
if (!message || typeof message !== "object" || Array.isArray(message)) {
|
|
144
|
+
this.fatal(new Error("Invalid app-server response")); return;
|
|
145
|
+
}
|
|
103
146
|
if (message.id !== undefined && message.method) {
|
|
104
147
|
// Headless bridge never approves commands or answers interactive prompts.
|
|
105
|
-
this.write({ id: message.id, error: { code: -32601, message: "Interactive requests unsupported by bridge" } });
|
|
148
|
+
try { this.write({ id: message.id, error: { code: -32601, message: "Interactive requests unsupported by bridge" } }); } catch {}
|
|
106
149
|
return;
|
|
107
150
|
}
|
|
108
151
|
if (message.id !== undefined) {
|
|
109
152
|
const waiter = this.pending.get(message.id);
|
|
110
|
-
if (waiter) { this.pending.delete(message.id);
|
|
153
|
+
if (waiter) { clearTimeout(waiter.timer); this.pending.delete(message.id);
|
|
111
154
|
if (message.error) {
|
|
112
155
|
const detail = typeof message.error.message === "string" ? message.error.message : "";
|
|
113
156
|
const error = waiter.method === "thread/resume" && /already has an active writer/i.test(detail)
|
|
@@ -123,19 +166,27 @@ export class AppServer {
|
|
|
123
166
|
}
|
|
124
167
|
const a = this.active, p = message.params;
|
|
125
168
|
if (!a || p?.threadId !== a.thread) return;
|
|
126
|
-
if (!a.turn) { a.early.push(message); return; }
|
|
169
|
+
if (!a.turn) { if (a.early.length < 500) a.early.push(message); return; }
|
|
127
170
|
if ((p.turnId ?? p.turn?.id) !== a.turn) return;
|
|
128
|
-
|
|
129
|
-
(!
|
|
171
|
+
const recordItem = (item: any) => {
|
|
172
|
+
if (item?.type === "agentMessage" && (!item.phase || item.phase === "final_answer") &&
|
|
173
|
+
typeof item.id === "string" && item.id.length > 0 && typeof item.text === "string" &&
|
|
174
|
+
(a.items.has(item.id) || a.items.size < 512)) a.items.set(item.id, item.text);
|
|
175
|
+
};
|
|
176
|
+
if (message.method === "item/completed") recordItem(p.item);
|
|
130
177
|
if (message.method === "turn/completed") {
|
|
131
178
|
this.active = undefined;
|
|
132
|
-
if (p.turn
|
|
133
|
-
for (const item of p.turn.items
|
|
179
|
+
if (p.turn?.status !== "completed") { a.reject(new Error(`Codex turn ${p.turn?.status ?? "unknown"}`)); return; }
|
|
180
|
+
for (const item of Array.isArray(p.turn.items) ? p.turn.items : []) recordItem(item);
|
|
134
181
|
const text = [...a.items.values()].join("\n").trim();
|
|
135
182
|
text ? a.resolve(text) : a.reject(new Error("Codex completed without a final reply"));
|
|
136
183
|
}
|
|
137
184
|
}
|
|
138
185
|
async thread(cwd: string, existing?: string, ephemeral = false, permissions: PermissionMode = this.permissions): Promise<string> {
|
|
186
|
+
if (typeof cwd !== "string" || !cwd.trim() || cwd.length > 4096 || APP_SERVER_CTRL_RE.test(cwd))
|
|
187
|
+
throw new Error("Invalid app-server cwd");
|
|
188
|
+
if (existing !== undefined && !validThreadId(existing))
|
|
189
|
+
throw new Error("Invalid app-server thread ID");
|
|
139
190
|
// Loaded-thread resume ignores MCP and developer-instruction overrides.
|
|
140
191
|
// Keep the original runtime policy; a different permission needs a new thread.
|
|
141
192
|
const configured = existing ? this.threadPermissions.get(existing) : undefined;
|
|
@@ -144,7 +195,9 @@ export class AppServer {
|
|
|
144
195
|
}
|
|
145
196
|
const result = await this.request("config/read", { includeLayers: false, cwd });
|
|
146
197
|
this.disabledMcp = {};
|
|
147
|
-
for (const name of Object.keys(result.config?.mcp_servers ?? {}))
|
|
198
|
+
for (const name of Object.keys(result.config?.mcp_servers ?? {})) {
|
|
199
|
+
if (!/^(?:__proto__|constructor|prototype)$/i.test(name)) this.disabledMcp[name] = { enabled: false };
|
|
200
|
+
}
|
|
148
201
|
const r = await this.request(existing ? "thread/resume" : "thread/start", {
|
|
149
202
|
...(existing ? { threadId: existing } : { ephemeral }), cwd, ...(this.model ? { model: this.model } : {}),
|
|
150
203
|
approvalPolicy: "never", sandbox: permissions === "full-access" ? "danger-full-access" : "read-only",
|
|
@@ -157,9 +210,11 @@ export class AppServer {
|
|
|
157
210
|
});
|
|
158
211
|
if (typeof r.thread?.id !== "string") throw new Error("App-server returned no thread ID");
|
|
159
212
|
this.threadPermissions.set(r.thread.id, permissions);
|
|
213
|
+
if (this.threadPermissions.size > 1024) this.threadPermissions.delete(this.threadPermissions.keys().next().value!);
|
|
160
214
|
return r.thread.id;
|
|
161
215
|
}
|
|
162
216
|
async readThread(thread: string): Promise<ThreadHistory> {
|
|
217
|
+
if (!validThreadId(thread)) throw new Error("Invalid app-server thread ID");
|
|
163
218
|
const result = await this.request("thread/read", {threadId:thread, includeTurns:true});
|
|
164
219
|
if (result.thread?.id !== thread || !Array.isArray(result.thread.turns)) throw new Error("Original thread history unavailable");
|
|
165
220
|
if (result.thread.turns.some((turn: any) => !Array.isArray(turn.items) || (turn.itemsView && turn.itemsView !== "full")))
|
|
@@ -167,11 +222,15 @@ export class AppServer {
|
|
|
167
222
|
return {id:thread, createdAt:result.thread.createdAt, turns:result.thread.turns};
|
|
168
223
|
}
|
|
169
224
|
async readLegacyThread(thread: string): Promise<ThreadHistory> {
|
|
225
|
+
if (!validThreadId(thread)) throw new Error("Invalid app-server thread ID");
|
|
170
226
|
if (!this.runtime?.legacyHome) return this.readThread(thread);
|
|
171
227
|
const reader = new AppServer(this.bin, undefined, undefined, this.permissions, {home:this.runtime.legacyHome});
|
|
172
228
|
try { await reader.start(); return await reader.readThread(thread); } finally { reader.close(); }
|
|
173
229
|
}
|
|
174
230
|
async nameThread(thread: string, name: string): Promise<void> {
|
|
231
|
+
if (!validThreadId(thread)) throw new Error("Invalid app-server thread ID");
|
|
232
|
+
if (typeof name !== "string" || !name.trim() || name.length > 256 || APP_SERVER_CTRL_RE.test(name))
|
|
233
|
+
throw new Error("Invalid app-server thread name");
|
|
175
234
|
await this.request("thread/name/set", {threadId:thread, name});
|
|
176
235
|
}
|
|
177
236
|
async generate(thread: string, text: string, effort: ReasoningEffort | undefined = this.effort): Promise<string> {
|
|
@@ -195,12 +254,32 @@ export class AppServer {
|
|
|
195
254
|
} catch (e) { this.fail(e instanceof Error ? e : new Error("Generation failed")); throw e; }
|
|
196
255
|
}
|
|
197
256
|
private fail(error: Error) {
|
|
198
|
-
for (const p of this.pending.values()) p.
|
|
257
|
+
for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(error); }
|
|
258
|
+
this.pending.clear();
|
|
199
259
|
if (this.active) { this.active.reject(error); this.active = undefined; }
|
|
200
260
|
}
|
|
261
|
+
private terminateChild() {
|
|
262
|
+
try { this.rl?.close(); } catch {}
|
|
263
|
+
this.rl = undefined;
|
|
264
|
+
const child = this.child;
|
|
265
|
+
if (!child) return;
|
|
266
|
+
try { child.stdin.end(); } catch {}
|
|
267
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
268
|
+
try { child.kill("SIGTERM"); } catch {}
|
|
269
|
+
if (!this.killTimer) {
|
|
270
|
+
this.killTimer = setTimeout(() => {
|
|
271
|
+
this.killTimer = undefined;
|
|
272
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
273
|
+
try { child.kill("SIGKILL"); } catch {}
|
|
274
|
+
}
|
|
275
|
+
}, 2_000);
|
|
276
|
+
this.killTimer.unref?.();
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
201
280
|
private fatal(error: Error) {
|
|
202
281
|
if (this.closed) return;
|
|
203
|
-
this.closed = true; this.fail(error); this.onFatal?.(); this.
|
|
282
|
+
this.closed = true; this.fail(error); this.onFatal?.(); this.terminateChild();
|
|
204
283
|
}
|
|
205
|
-
close() { this.closed = true; this.fail(new Error("App-server stopped")); this.
|
|
284
|
+
close() { this.closed = true; this.fail(new Error("App-server stopped")); this.terminateChild(); }
|
|
206
285
|
}
|
package/codex/bots-config.ts
CHANGED
|
@@ -1,36 +1,57 @@
|
|
|
1
|
-
import { readFileSync, realpathSync, mkdirSync } from "node:fs";
|
|
1
|
+
import { readFileSync, realpathSync, mkdirSync, lstatSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
-
import { resolveConfig, type BridgeConfig, type IdentitySettings } from "./config.ts";
|
|
4
|
+
import { assertDirectoryAncestors, reservedProfileStem, resolveConfig, type BridgeConfig, type IdentitySettings } from "./config.ts";
|
|
5
5
|
|
|
6
6
|
export interface BotConfig extends BridgeConfig { name: string }
|
|
7
7
|
export function defaultRegistry(home = homedir()) { return join(home, ".agentschat/codex-bots.json"); }
|
|
8
8
|
export function loadBots(file = defaultRegistry(), home = homedir()): BotConfig[] {
|
|
9
|
+
assertDirectoryAncestors(dirname(file));
|
|
9
10
|
let doc: any;
|
|
10
|
-
try {
|
|
11
|
+
try {
|
|
12
|
+
const info = lstatSync(file);
|
|
13
|
+
if (info.isSymbolicLink() || !info.isFile() || info.size > 1_048_576) throw new Error("Invalid registry file");
|
|
14
|
+
doc = JSON.parse(readFileSync(file, "utf8"));
|
|
15
|
+
} catch { throw new Error("Cannot read bot registry JSON"); }
|
|
11
16
|
const object = (x: any) => x && typeof x === "object" && !Array.isArray(x);
|
|
12
17
|
const fields = (x: any, keys: string[]) => {
|
|
13
|
-
if (!object(x) || Object.
|
|
18
|
+
if (!object(x) || Object.getOwnPropertyNames(x).some(k => !keys.includes(k))) throw new Error("Unknown or invalid bot registry field");
|
|
14
19
|
};
|
|
15
|
-
const text = (x: unknown): x is string => typeof x === "string" && x.trim().length > 0;
|
|
20
|
+
const text = (x: unknown, max = 4096): x is string => typeof x === "string" && x.trim().length > 0 && x.length <= max && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(x);
|
|
21
|
+
const reservedNames = new Set(["__proto__", "constructor", "prototype", ...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase())]);
|
|
22
|
+
const reserved = (s: string) => reservedNames.has(s.toLowerCase());
|
|
16
23
|
fields(doc, ["version", "default_workdir", "codex_bin", "bots"]);
|
|
17
|
-
if (doc.version !== 1 || !Array.isArray(doc.bots)) throw new Error("Registry requires version 1 and bots array");
|
|
24
|
+
if (doc.version !== 1 || !Array.isArray(doc.bots) || doc.bots.length > 128) throw new Error("Registry requires version 1 and bots array");
|
|
18
25
|
for (const k of ["default_workdir", "codex_bin"]) if (doc[k] !== undefined && !text(doc[k])) throw new Error(`Invalid ${k}`);
|
|
19
|
-
const path = (value: string) => value
|
|
26
|
+
const path = (value: string) => /^~[\\/]/.test(value) ? join(home, value.slice(2)) : isAbsolute(value) ? value : resolve(dirname(file), value);
|
|
20
27
|
const defaultDir = doc.default_workdir ? path(doc.default_workdir) : join(home, ".agentschat/workspace");
|
|
21
28
|
const names = new Set<string>(), identities = new Set<string>();
|
|
22
29
|
const bots: BotConfig[] = [];
|
|
23
30
|
for (const bot of doc.bots) {
|
|
24
31
|
fields(bot, ["name", "profile", "workdir", "enabled", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "state_root", "codex_home_mode"]);
|
|
25
|
-
if (!text(bot.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(bot.name) || names.has(bot.name)) throw new Error("Bot names must be unique simple labels");
|
|
32
|
+
if (!text(bot.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(bot.name) || reserved(bot.name) || names.has(bot.name)) throw new Error("Bot names must be unique simple labels");
|
|
26
33
|
names.add(bot.name);
|
|
27
34
|
if (bot.enabled !== undefined && typeof bot.enabled !== "boolean") throw new Error("Invalid bot enabled flag");
|
|
28
35
|
if (bot.enabled === false) continue;
|
|
29
36
|
if (!text(bot.profile) || (bot.workdir !== undefined && !text(bot.workdir))) throw new Error(`Bot ${bot.name} needs a profile and valid optional workdir`);
|
|
30
37
|
// Registry profiles are named, centrally stored identities, not project-relative files.
|
|
31
|
-
if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile)
|
|
32
|
-
|
|
33
|
-
|
|
38
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$/.test(bot.profile) || bot.profile.includes("..") ||
|
|
39
|
+
reservedProfileStem(bot.profile)) {
|
|
40
|
+
throw new Error(`Bot ${bot.name}: profile must be a central profile name`);
|
|
41
|
+
}
|
|
42
|
+
const directoryLeaf = (dir: string) => {
|
|
43
|
+
const info = lstatSync(dir, { throwIfNoEntry: false });
|
|
44
|
+
if (info && (info.isSymbolicLink() || !info.isDirectory())) throw new Error("Bot workdir must be a directory, not a symlink");
|
|
45
|
+
assertDirectoryAncestors(dir);
|
|
46
|
+
};
|
|
47
|
+
if (!doc.default_workdir && !bot.workdir) {
|
|
48
|
+
directoryLeaf(join(home, ".agentschat"));
|
|
49
|
+
directoryLeaf(defaultDir);
|
|
50
|
+
mkdirSync(defaultDir, { recursive: true, mode: 0o700 });
|
|
51
|
+
}
|
|
52
|
+
const workdir = bot.workdir ? path(bot.workdir) : defaultDir;
|
|
53
|
+
directoryLeaf(workdir);
|
|
54
|
+
const cwd = realpathSync(workdir);
|
|
34
55
|
const settings: IdentitySettings = {};
|
|
35
56
|
for (const k of ["agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "codex_home_mode"] as const) if (bot[k] !== undefined) (settings as any)[k] = bot[k];
|
|
36
57
|
if (bot.state_root !== undefined) { if (!text(bot.state_root)) throw new Error("Invalid state_root"); settings.state_root = path(bot.state_root); }
|