Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(agent): a bounded pty_session tool, so an agent can drive an interactive process (#176)

Abdurrahman Fakhrul241780d967a5
diff --git a/docs/AGENT-PTY-DESIGN.md b/docs/AGENT-PTY-DESIGN.md
new file mode 100644
index 00000000..629a191f
--- /dev/null
+++ b/docs/AGENT-PTY-DESIGN.md
@@ -0,0 +1,65 @@
+# PTY for the agent: design note
+
+Item 5 in `docs/AGENT-CODING-PLAN.md`. Written before implementation because this is the
+highest-blast-radius tool in the catalog: a PTY is an interactive shell, and an agent driving
+one can do anything the owner's shell can do, including things `exec_run` cannot (answer a
+prompt, run a REPL, hold a lock, keep a server up).
+
+## What exists
+
+- `app/api/v1/term/{open,input,resize,stream,close}` routes.
+- `lib/host/pty.ts` via `lib/host/terminal-api.ts`: `openPty`, `attachPty`, `writePty`,
+ `resizePty`, `closePty`, `hasPty`.
+- A rate limit of 20 opens per window per actor in `term-service.ts`, and `term.open`
+ already writes to the audit trail.
+- The CLI exposes it as `mso term open|input|resize|stream|close`.
+
+No MCP tool exposes any of it. So an agent cannot drive a long build, a REPL, or any
+program that needs stdin to stay open. `exec_run` is one-shot with a 30s budget and
+`exec_job_start` is fire-and-forget with a status read, which is genuinely different.
+
+## Why this is dangerous, stated plainly
+
+- `exec_run` is bounded: one command, captured output, one exit code. A PTY is unbounded
+ in time and interaction.
+- A PTY can hold a lock, a watcher, or a server. Left open it outlives the turn.
+- A PTY can sit at an interactive password prompt. An agent typing into it is one bad
+ guess from a lockout.
+- Output is a stream, not a value. Returning an unbounded stream into a model context is
+ how a session gets poisoned.
+
+## Design, chosen to keep the blast radius equal to `exec_run` rather than larger
+
+1. **One tool, not five.** `pty_session` with an `action` field: `open`, `write`, `read`,
+ `close`, `list`. Five separate tools would tempt a model to call them independently and
+ lose the correlation; one tool with an explicit action makes the session id the subject
+ of every call.
+2. **Every call is bounded.** `read` takes `max_bytes` (default 8 KiB, hard cap 32 KiB) and
+ `since_offset`, returning `{ output, nextOffset, truncated }`. It never returns an
+ unbounded stream, so a chatty process cannot flood the context.
+3. **Sessions expire.** A session that nobody reads or writes for N minutes is closed and
+ reaped, so an abandoned PTY cannot hold a lock forever. The tool reports `expired`
+ rather than pretending the session still exists.
+4. **Owner-scoped.** A session belongs to the principal that opened it. Another principal
+ gets not-found, never forbidden, so existence does not leak. This mirrors the
+ background-subagent rule just added.
+5. **No environment widening.** The PTY inherits exactly the environment the existing
+ `exec_run` path gives a command. No extra secrets.
+6. **Audit every action.** `term.open`, `term.write`, `term.close` already exist as audit
+ actions for the CLI; reuse them rather than inventing a parallel trail.
+7. **Scope `exec`.** Opening a shell is exec-class authority. It is never available at read
+ or write scope, and it respects the same `max_scope` ceiling a subagent inherits.
+
+## What I will NOT do
+
+- No `stream` tool. Streaming into a model is not a bounded operation. Polling `read` with
+ an offset is the honest version.
+- No auto-answer of password or sudo prompts. If the read output looks like a credential
+ prompt, the tool says so and stops; it does not guess.
+- No PTY for a subagent unless the parent already has `exec` scope.
+
+## Gate
+
+Same as before: bounded tools, split files to hold the ratchet, targeted tests that use a
+real PTY, then the 12-gate runner, then a PR. If the real-PTY tests are flaky on the CI
+image, say so and gate them on an environment check rather than letting them become noise.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 58957645..c33ac71f 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
+- `agent` a bounded pty_session tool, so an agent can drive an interactive process
- `agent` background subagents, so a parent can keep working in parallel (#175)
- `agent` surgical edit, content search, glob and a todo list (#173)
- `perf` hydration mark chain, and the LCP conclusion it overturns
diff --git a/docs/README.md b/docs/README.md
index 7797a843..356b81fa 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -32,6 +32,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`COGNITIVE-RUNTIME.md`](./COGNITIVE-RUNTIME.md) | Provider-neutral MCP/session/context/tool-routing runtime and benchmark contract |
| [`AGENT-BOOTSTRAP.md`](./AGENT-BOOTSTRAP.md) | Canonical first-call sequence and capability-parity matrix across CLI, MCP, and Alfa |
| [`AGENT-CODING-PLAN.md`](./AGENT-CODING-PLAN.md) | Audited coding-capability gaps in the MCP catalog, the four tools added to close them, and what stays out of scope |
+| [`AGENT-PTY-DESIGN.md`](./AGENT-PTY-DESIGN.md) | Why an agent-driven PTY is the highest-blast-radius tool in the catalog, and the bounds that keep it equal to exec_run |
| [`RASMIC.md`](./RASMIC.md) | Risk-aware orchestration, repo-local memory/evidence, collision detection and recipe/script promotion |
| [`MEMORY-GRAPH.md`](./MEMORY-GRAPH.md) | Owner Memory app: vault notes, project knowledge, agent memory, layouts and limits |
| [`AGENT-VAULT.md`](./AGENT-VAULT.md) | Separate private repository agent-progress vaults, source/data boundaries and Obsidian use |
diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.md
index 03eb1319..be818ef8 100644
--- a/docs/generated/MCP-CATALOG.md
+++ b/docs/generated/MCP-CATALOG.md
@@ -4,18 +4,18 @@
## Full MSO catalog
-<!-- mcp-toolset: server=1.17.0 version=2026.10.18.3 tools=126 read=62 write=39 exec=25 -->
+<!-- mcp-toolset: server=1.17.0 version=2026.10.18.3 tools=127 read=62 write=39 exec=26 -->
| Fact | Current source value |
|---|---:|
| MCP server | `1.17.0` |
| Toolset | `2026.10.18.3` |
| Toolset changed at | `2026-10-18T13:24:00+00:00` |
-| Transport tools | **128** |
-| Model/operator tools | **126** |
+| Transport tools | **129** |
+| Model/operator tools | **127** |
| Read | **62** |
| Write | **39** |
-| Exec | **25** |
+| Exec | **26** |
| App-only bridges | **2** |
### Read (62)
@@ -125,7 +125,7 @@
- `workflow_finish`
- `workflow_start`
-### Exec (25)
+### Exec (26)
- `a2a_handoff`
- `a2a_message_send`
@@ -149,6 +149,7 @@
- `project_function_call`
- `project_mcp_call`
- `project_mcp_tools`
+- `pty_session`
- `tool_forge_evaluate`
- `tool_forge_promote`
- `workflow_graph`
@@ -160,17 +161,17 @@
## ChatGPT model profile
-<!-- mcp-chatgpt-profile: server=1.17.0 version=2026.10.18.3 tools=126 read=62 write=39 exec=25 app-only=2 total=128 -->
+<!-- mcp-chatgpt-profile: server=1.17.0 version=2026.10.18.3 tools=127 read=62 write=39 exec=26 app-only=2 total=129 -->
The ChatGPT profile automatically projects the complete MSO-owned generic model/operator catalog. OAuth scope is still enforced independently; app-only compatibility bridges stay app-only, and project-owned MCP tool names remain dynamic data behind the generic project bridge.
| Fact | Current source value |
|---|---:|
-| ChatGPT transport tools | **128** |
-| ChatGPT model/operator tools | **126** |
+| ChatGPT transport tools | **129** |
+| ChatGPT model/operator tools | **127** |
| Read | **62** |
| Write | **39** |
-| Exec | **25** |
+| Exec | **26** |
| App-only bridges | **2** |
### ChatGPT read (62)
@@ -280,7 +281,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `workflow_finish`
- `workflow_start`
-### ChatGPT exec (25)
+### ChatGPT exec (26)
- `a2a_handoff`
- `a2a_message_send`
@@ -304,6 +305,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `project_function_call`
- `project_mcp_call`
- `project_mcp_tools`
+- `pty_session`
- `tool_forge_evaluate`
- `tool_forge_promote`
- `workflow_graph`
diff --git a/lib/contracts/audit.ts b/lib/contracts/audit.ts
index 52fda5e1..26a7d1e8 100644
--- a/lib/contracts/audit.ts
+++ b/lib/contracts/audit.ts
@@ -5,6 +5,7 @@ export type AuditAction =
| "exec.job.start"
| "exec.job.cancel"
| "term.open"
+ | "term.write"
| "term.close"
| "fs.write"
| "fs.delete"
diff --git a/lib/host/pty.ts b/lib/host/pty.ts
index c1154ab6..e7e002b9 100644
--- a/lib/host/pty.ts
+++ b/lib/host/pty.ts
@@ -7,8 +7,11 @@
// boundary to inspect, and an interactive shell composes commands from
// fragments (history, completion, editors) anyway. The gate is the same as
// every /api/v1 route: signed session cookie + approved device. Session
-// open/close are audited (term.open / term.close); keystrokes are not
-// (high-volume, and the owner has a full shell by design).
+// open/close are audited (term.open / term.close). The browser terminal does
+// not audit keystrokes (high-volume, and the owner has a full shell by design),
+// but the AGENT-side pty_session tool does: it logs term.write per call, because
+// "opened a shell" and "typed a command into a shell" are different acts and
+// collapsing them would hide the second one from forensics.
import { spawn } from "node-pty";
import type { IPty } from "node-pty";
import { createHash, randomBytes } from "crypto";
diff --git a/lib/mcp/mcp-only-reasons.ts b/lib/mcp/mcp-only-reasons.ts
index f39b5847..d9f3fe7e 100644
--- a/lib/mcp/mcp-only-reasons.ts
+++ b/lib/mcp/mcp-only-reasons.ts
@@ -109,4 +109,5 @@ export const MCP_ONLY: Record<string, string> = {
"render.mso.block": "the compact Block is a ChatGPT MCP Apps presentation target for validation/action/CRUD handoff; Alfa already has native forms and approval cards",
"render.mso.page": "the full Page is a ChatGPT MCP Apps presentation target; Alfa already is an MSO presentation target and does not render another copy of itself",
"render.mso.surface": "app-only compatibility alias for cached pre-Page widgets; Alfa has no reason to expose the retired presentation name",
+ "pty.session": "external coding agents need bounded interactive PTY sessions for interactive commands and long pipelines; in-shell Alfa already runs inside the native MSO terminal UI and does not need a headless pty tool",
};
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index d6ec9ea6..8af5e53d 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -73,6 +73,7 @@ describe("MCP rate limits mirror the routes", () => {
const ROUTE_LIMITS: Record<string, number> = {
"fs.write": 120, "fs.edit": 120, "fs.mkdir": 120, "fs.move": 120, "fs.copy": 60,
"fs.delete": 60, "fs.upload": 20, "exec": 60, "managed-app": 12, "camoufox": 12,
+ "term.open": 20,
};
const MCP_NATIVE_LIMITS: Record<string, number> = {
"flow.run": 20, "flow.manage": 20, "workflow.graph": 20, "agent.session.open": 20, "project.mcp.manage": 20, "project.asset.attach": 20,
diff --git a/lib/mcp/tools-pty.test.ts b/lib/mcp/tools-pty.test.ts
new file mode 100644
index 00000000..dbbe5e48
--- /dev/null
+++ b/lib/mcp/tools-pty.test.ts
@@ -0,0 +1,187 @@
+import { afterAll, describe, expect, it } from "vitest";
+import { spawn } from "node-pty";
+import { PTY_TOOLS } from "./tools-pty";
+
+let canSpawn = false;
+try {
+ const p = spawn(process.platform === "win32" ? "cmd.exe" : "/bin/sh", [], { cols: 80, rows: 24 });
+ p.kill();
+ canSpawn = true;
+} catch {
+ canSpawn = false;
+}
+
+const tool = PTY_TOOLS[0];
+const contextA = { principal: "mcp-client:pty-tester-a", scope: "exec" as const };
+const contextB = { principal: "mcp-client:pty-tester-b", scope: "exec" as const };
+const openedSessions: string[] = [];
+
+async function pollRead(
+ sessionId: string,
+ context: typeof contextA,
+ predicate: (out: string) => boolean,
+ sinceOffset = 0,
+ timeoutMs = 4000,
+) {
+ const start = Date.now();
+ let res = (await tool.run({ action: "read", sessionId, since_offset: sinceOffset }, context)) as {
+ output: string;
+ nextOffset: number;
+ truncated: boolean;
+ promptSuspected?: boolean;
+ exited?: boolean;
+ exitCode?: number;
+ };
+ while (!predicate(res.output) && Date.now() - start < timeoutMs) {
+ await new Promise((r) => setTimeout(r, 60));
+ res = (await tool.run({ action: "read", sessionId, since_offset: sinceOffset }, context)) as typeof res;
+ }
+ return res;
+}
+
+afterAll(async () => {
+ for (const id of openedSessions) {
+ try {
+ await tool.run({ action: "close", sessionId: id }, contextA);
+ } catch {
+ // ignore
+ }
+ }
+});
+
+describe("pty_session tool", () => {
+ it.skipIf(!canSpawn)(
+ "1. open returns session id, write echoes into read output, nextOffset advances",
+ async () => {
+ const opened = (await tool.run({ action: "open" }, contextA)) as {
+ sessionId: string;
+ cols: number;
+ rows: number;
+ };
+ expect(opened.sessionId).toBeDefined();
+ expect(opened.cols).toBe(120);
+ expect(opened.rows).toBe(30);
+ openedSessions.push(opened.sessionId);
+
+ const writeRes = (await tool.run(
+ { action: "write", sessionId: opened.sessionId, data: "echo PTY_TEST_123\n" },
+ contextA,
+ )) as { ok: boolean; bytesWritten: number };
+ expect(writeRes.ok).toBe(true);
+ expect(writeRes.bytesWritten).toBeGreaterThan(0);
+
+ const readRes = await pollRead(opened.sessionId, contextA, (o) => o.includes("PTY_TEST_123"));
+ expect(readRes.output).toContain("PTY_TEST_123");
+ expect(readRes.nextOffset).toBeGreaterThan(0);
+ },
+ );
+
+ it.skipIf(!canSpawn)("2. second read with since_offset does not repeat earlier bytes", async () => {
+ const opened = (await tool.run({ action: "open" }, contextA)) as { sessionId: string };
+ openedSessions.push(opened.sessionId);
+
+ await tool.run({ action: "write", sessionId: opened.sessionId, data: "echo ECHO_ONCE_A\n" }, contextA);
+ const read1 = await pollRead(opened.sessionId, contextA, (o) => o.includes("ECHO_ONCE_A"));
+ expect(read1.output).toContain("ECHO_ONCE_A");
+
+ const read2 = (await tool.run(
+ { action: "read", sessionId: opened.sessionId, since_offset: read1.nextOffset },
+ contextA,
+ )) as { output: string; nextOffset: number };
+ expect(read2.output).not.toContain("ECHO_ONCE_A");
+ });
+
+ it.skipIf(!canSpawn)("3. max_bytes is respected and truncated is true when more is pending", async () => {
+ const opened = (await tool.run({ action: "open" }, contextA)) as { sessionId: string };
+ openedSessions.push(opened.sessionId);
+
+ await tool.run(
+ { action: "write", sessionId: opened.sessionId, data: "echo HELLO_PTY_LONG_STRING_ECHO\n" },
+ contextA,
+ );
+ await pollRead(opened.sessionId, contextA, (o) => o.includes("LONG_STRING"));
+
+ const bounded = (await tool.run(
+ { action: "read", sessionId: opened.sessionId, since_offset: 0, max_bytes: 6 },
+ contextA,
+ )) as { output: string; nextOffset: number; truncated: boolean };
+ expect(bounded.output.length).toBeLessThanOrEqual(6);
+ expect(bounded.truncated).toBe(true);
+ });
+
+ it.skipIf(!canSpawn)("4. different principal cannot read, write or close the session (not-found)", async () => {
+ const opened = (await tool.run({ action: "open" }, contextA)) as { sessionId: string };
+ openedSessions.push(opened.sessionId);
+
+ await expect(tool.run({ action: "read", sessionId: opened.sessionId }, contextB)).rejects.toThrow(
+ /Unknown terminal session/,
+ );
+ await expect(
+ tool.run({ action: "write", sessionId: opened.sessionId, data: "echo nope\n" }, contextB),
+ ).rejects.toThrow(/Unknown terminal session/);
+ await expect(tool.run({ action: "close", sessionId: opened.sessionId }, contextB)).rejects.toThrow(
+ /Unknown terminal session/,
+ );
+ });
+
+ it.skipIf(!canSpawn)("5. close makes later read report session gone or exited", async () => {
+ const opened = (await tool.run({ action: "open" }, contextA)) as { sessionId: string };
+ const closeRes = (await tool.run({ action: "close", sessionId: opened.sessionId }, contextA)) as {
+ ok: boolean;
+ closed: boolean;
+ };
+ expect(closeRes.ok).toBe(true);
+
+ let exitedOrGone = false;
+ const start = Date.now();
+ while (!exitedOrGone && Date.now() - start < 3000) {
+ try {
+ const readRes = (await tool.run({ action: "read", sessionId: opened.sessionId }, contextA)) as {
+ exited?: boolean;
+ };
+ if (readRes.exited) exitedOrGone = true;
+ } catch (e) {
+ if (/Unknown terminal session/i.test(String(e))) exitedOrGone = true;
+ }
+ if (!exitedOrGone) await new Promise((r) => setTimeout(r, 50));
+ }
+ expect(exitedOrGone).toBe(true);
+ });
+
+ it.skipIf(!canSpawn)("6. list shows only the caller's sessions", async () => {
+ const openedA = (await tool.run({ action: "open" }, contextA)) as { sessionId: string };
+ const openedB = (await tool.run({ action: "open" }, contextB)) as { sessionId: string };
+ openedSessions.push(openedA.sessionId);
+
+ const listA = (await tool.run({ action: "list" }, contextA)) as {
+ sessions: Array<{ sessionId: string }>;
+ };
+ const listB = (await tool.run({ action: "list" }, contextB)) as {
+ sessions: Array<{ sessionId: string }>;
+ };
+
+ expect(listA.sessions.some((s) => s.sessionId === openedA.sessionId)).toBe(true);
+ expect(listA.sessions.some((s) => s.sessionId === openedB.sessionId)).toBe(false);
+
+ expect(listB.sessions.some((s) => s.sessionId === openedB.sessionId)).toBe(true);
+ expect(listB.sessions.some((s) => s.sessionId === openedA.sessionId)).toBe(false);
+
+ await tool.run({ action: "close", sessionId: openedB.sessionId }, contextB);
+ });
+
+ it.skipIf(!canSpawn)("7. fake credential-prompt output sets promptSuspected", async () => {
+ const opened = (await tool.run({ action: "open" }, contextA)) as { sessionId: string };
+ openedSessions.push(opened.sessionId);
+
+ await tool.run(
+ { action: "write", sessionId: opened.sessionId, data: "printf 'Password: '\n" },
+ contextA,
+ );
+ const readRes = await pollRead(opened.sessionId, contextA, (o) => o.toLowerCase().includes("password:"));
+ expect(readRes.promptSuspected).toBe(true);
+ });
+
+ it("rejects unknown action", async () => {
+ await expect(tool.run({ action: "invalid" }, contextA)).rejects.toThrow(/action must be/);
+ });
+});
diff --git a/lib/mcp/tools-pty.ts b/lib/mcp/tools-pty.ts
new file mode 100644
index 00000000..6707b865
--- /dev/null
+++ b/lib/mcp/tools-pty.ts
@@ -0,0 +1,171 @@
+import { createHash } from "crypto";
+import { attachPty, closePty, hasPty, openPty, writePty } from "@/lib/host/terminal-api";
+import { opt, S, str, type McpTool } from "./tool-kit";
+import { requireWorkflowExecCwd } from "./workflow-workspace-guard";
+
+const PROMPT_REGEX = /(?:password:|passphrase|sudo password|\[sudo\])/i;
+const sessionCreatedAt = new Map<string, number>();
+
+function listSessions(owner: string) {
+ const g = globalThis as {
+ __osPtySessions?: Map<string, { id: string; ownerHash: string; dead: boolean; exitCode: number }>;
+ };
+ const sessions = g.__osPtySessions;
+ if (!sessions) return { sessions: [] };
+ const hash = createHash("sha256").update(owner).digest("hex");
+ const list: Array<{ sessionId: string; createdAt?: number; dead: boolean; exitCode?: number }> = [];
+ for (const s of sessions.values()) {
+ if (s.ownerHash === hash) {
+ list.push({
+ sessionId: s.id,
+ ...(sessionCreatedAt.has(s.id) ? { createdAt: sessionCreatedAt.get(s.id) } : {}),
+ dead: Boolean(s.dead),
+ ...(s.dead ? { exitCode: s.exitCode } : {}),
+ });
+ }
+ }
+ return { sessions: list };
+}
+
+function readSession(sessionId: string, owner: string, sinceOffset: number, maxBytes: number) {
+ let output = "";
+ let nextOffset = sinceOffset;
+ let truncated = false;
+ let exited: boolean | undefined;
+ let exitCode: number | undefined;
+
+ const detach = attachPty(sessionId, owner, sinceOffset, {
+ onData: (chunk, end) => {
+ if (truncated) return;
+ const chunkStart = end - chunk.length;
+ const remaining = maxBytes - output.length;
+ if (remaining <= 0) {
+ truncated = true;
+ return;
+ }
+ if (chunk.length <= remaining) {
+ output += chunk;
+ nextOffset = end;
+ } else {
+ output += chunk.slice(0, remaining);
+ nextOffset = chunkStart + remaining;
+ truncated = true;
+ }
+ },
+ onExit: (code) => {
+ exited = true;
+ exitCode = code;
+ },
+ });
+ detach();
+
+ const promptSuspected = PROMPT_REGEX.test(output);
+ return {
+ output,
+ nextOffset,
+ truncated,
+ ...(exited !== undefined ? { exited, exitCode } : {}),
+ ...(promptSuspected ? { promptSuspected: true } : {}),
+ };
+}
+
+const PTY_INPUT_PROPERTIES = {
+ action: {
+ type: "string",
+ enum: ["open", "write", "read", "list", "close"],
+ description: "PTY action: open, write, read, list, or close.",
+ },
+ sessionId: { type: "string", description: "Terminal session identifier." },
+ cwd: { type: "string", description: "Working directory for open. Defaults to owner home." },
+ cols: { type: "number", description: "Terminal columns for open. Default 120." },
+ rows: { type: "number", description: "Terminal rows for open. Default 30." },
+ data: { type: "string", description: "Input characters or bytes for write. Maximum 4 KiB." },
+ max_bytes: { type: "number", description: "Maximum output bytes to read. Default 8192, cap 32768." },
+ since_offset: { type: "number", description: "Absolute replay offset for read. Default 0." },
+};
+
+export const PTY_TOOLS: McpTool[] = [
+ {
+ name: "pty_session",
+ title: "Interactive Terminal Session",
+ scope: "exec",
+ limit: {
+ key: "term.open",
+ max: 20,
+ windowMs: 60_000,
+ actionLimits: {
+ write: { max: 120, windowMs: 60_000 },
+ read: { max: 240, windowMs: 60_000 },
+ list: { max: 60, windowMs: 60_000 },
+ close: { max: 60, windowMs: 60_000 },
+ },
+ },
+ audit: {
+ action: "term.open" as const,
+ targetArg: "sessionId",
+ outcome: (r) => {
+ const res = r as { sessionId?: string; closed?: boolean; bytesWritten?: number } | undefined;
+ if (res?.closed !== undefined) return { ok: true, action: "term.close", detail: `closed: ${res.closed}` };
+ if (res?.sessionId) return { ok: true, action: "term.open", detail: `session ${res.sessionId.slice(0, 8)}` };
+ // Keystrokes are their own forensic event: "opened a shell" and "typed a command
+ // into a shell" are not the same act, and collapsing them hides the second one.
+ if (typeof res?.bytesWritten === "number") return { ok: true, action: "term.write", detail: `wrote ${res.bytesWritten}b` };
+ return { ok: true, action: "term.open" };
+ },
+ },
+ actionContract: {
+ phase: "execute",
+ target: "terminal-pty",
+ sourceOfTruth: "live",
+ confirmation: "contextual",
+ presentation: "structured",
+ },
+ description:
+ "Interactive PTY session for commands requiring a real terminal. Bounded polling over absolute-offset replay ring. Actions: open, write, read, list, close.",
+ annotations: { destructiveHint: true, openWorldHint: true },
+ result: {
+ maxTextBytes: 48 * 1024,
+ overflowHint: "PTY output is polled with max_bytes and since_offset; read next chunk if truncated.",
+ },
+ inputSchema: S(PTY_INPUT_PROPERTIES, ["action"]),
+ run: async (a, context) => {
+ const owner = context.principal ?? context.workflowActor ?? context.actor;
+ if (!owner) throw new Error("principal is required");
+ const action = a.action;
+ if (action === "open") {
+ const cols = typeof a.cols === "number" && a.cols > 0 ? a.cols : 120;
+ const rows = typeof a.rows === "number" && a.rows > 0 ? a.rows : 30;
+ const cwd = opt(a, "cwd");
+ await requireWorkflowExecCwd(context, cwd);
+ const { id } = await openPty({ cols, rows, cwd, owner });
+ sessionCreatedAt.set(id, Date.now());
+ return { sessionId: id, cols, rows };
+ }
+ if (action === "write") {
+ const sessionId = str(a, "sessionId");
+ if (typeof a.data !== "string") throw new Error("data must be a string");
+ const byteLen = Buffer.byteLength(a.data, "utf8");
+ if (byteLen > 4096) throw new Error("data exceeds 4 KiB limit");
+ writePty(sessionId, owner, a.data);
+ return { ok: true, bytesWritten: byteLen };
+ }
+ if (action === "read") {
+ const sessionId = str(a, "sessionId");
+ const requestedMax = typeof a.max_bytes === "number" && a.max_bytes > 0 ? a.max_bytes : 8192;
+ const maxBytes = Math.min(requestedMax, 32768);
+ const sinceOffset = typeof a.since_offset === "number" && a.since_offset >= 0 ? a.since_offset : 0;
+ return readSession(sessionId, owner, sinceOffset, maxBytes);
+ }
+ if (action === "list") {
+ return listSessions(owner);
+ }
+ if (action === "close") {
+ const sessionId = str(a, "sessionId");
+ if (!hasPty(sessionId, owner)) throw new Error(`Unknown terminal session`);
+ const closed = closePty(sessionId, owner);
+ return { ok: true, closed };
+ }
+ throw new Error("action must be open, write, read, list, or close");
+ },
+ },
+];
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 97ec1a17..9c35170b 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -26,8 +26,9 @@ import { SUBAGENT_TOOLS } from "./tools-subagents";
import { BLOCK_TOOLS, LIST_TOOLS, NATIVE_UI_PROBE_TOOLS, SURFACE_TOOLS } from "./tools-ui";
import type { McpTool } from "./tool-kit";
+import { PTY_TOOLS } from "./tools-pty";
import { EDIT_TOOLS } from "./tools-edit";
import { MUTATE_TOOLS } from "./tools-mutate";
import { NAVIGATE_TOOLS } from "./tools-navigate";
-export const TOOLS: McpTool[] = [...AGENT_VAULT_TOOLS, ...FLOW_TOOLS, ...AGENT_OPEN_TOOLS, ...PROJECT_ASSET_TOOLS, ...PROJECT_MCP_MANAGE_TOOLS, ...SESSION_ARTIFACT_TOOLS, ...READ_TOOLS, ...NAVIGATE_TOOLS, ...FILE_TRANSFER_READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...JEV_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...ORGANIZATION_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...NATIVE_UI_PROBE_TOOLS, ...BLOCK_TOOLS, ...LIST_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...INTEGRATION_TOOLS, ...EDIT_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
+export const TOOLS: McpTool[] = [...AGENT_VAULT_TOOLS, ...FLOW_TOOLS, ...AGENT_OPEN_TOOLS, ...PROJECT_ASSET_TOOLS, ...PROJECT_MCP_MANAGE_TOOLS, ...SESSION_ARTIFACT_TOOLS, ...READ_TOOLS, ...NAVIGATE_TOOLS, ...FILE_TRANSFER_READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...JEV_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...ORGANIZATION_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...NATIVE_UI_PROBE_TOOLS, ...BLOCK_TOOLS, ...LIST_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...INTEGRATION_TOOLS, ...EDIT_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS, ...PTY_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));