agentenv-vfs 0.4.2__py3-none-any.whl

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.
@@ -0,0 +1 @@
1
+ """agentenv-vfs: an agent-env plugin that gives an agent another env's MCP tools as shell commands (agentvfs)."""
@@ -0,0 +1 @@
1
+ type = "file_artifact_universe"
@@ -0,0 +1,25 @@
1
+ """Copy the agentvfs env's log of the agent's shell lines and tool calls into the run's record: run_code on the
2
+ agentvfs env (standard library only; agent-env may run it on the env's host). Returns a summary and the log."""
3
+ import base64
4
+ import collections
5
+ import json
6
+ import urllib.request
7
+
8
+ MAX_ROWS = 20000 # past this the log keeps its first rows, and says so
9
+
10
+
11
+ def run(input):
12
+ env = input["env"]
13
+ body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "data/get", "params": {"paths": ["calls.jsonl"]}}).encode()
14
+ req = urllib.request.Request(f"{env['url'].rstrip('/')}/agentenv", data=body, method="POST",
15
+ headers={"Content-Type": "application/json", **(env.get("headers") or {})})
16
+ with urllib.request.urlopen(req, timeout=120) as r:
17
+ reply = json.loads(r.read().decode())
18
+ if "error" in reply:
19
+ raise RuntimeError(f"data/get failed: {reply['error']}")
20
+ data = b"".join(base64.b64decode(p["file"]["bytes"]) for p in reply["result"]["parts"] if p.get("kind") == "file")
21
+ rows = [json.loads(line) for line in data.decode().splitlines() if line.strip()]
22
+ calls = [r for r in rows if r["kind"] == "call"]
23
+ return {"lines": len(rows) - len(calls), "calls": len(calls), "failed_calls": sum(not r["ok"] for r in calls),
24
+ "by_tool": dict(collections.Counter(r["tool"] for r in calls).most_common()),
25
+ "truncated": len(rows) > MAX_ROWS, "log": rows[:MAX_ROWS]}
agentenv_vfs/cli.py ADDED
@@ -0,0 +1,46 @@
1
+ """``agent-env vfs``: give a bundle's agent the agentvfs interface."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import click
8
+
9
+ from agentenv_vfs.wrap import WrapError, add_env, wrap_bundle
10
+
11
+
12
+ @click.group("vfs")
13
+ def vfs() -> None:
14
+ """Work through agentvfs: an env's tools as shell commands in a Mirage workspace."""
15
+
16
+
17
+ @vfs.command("wrap")
18
+ @click.argument("bundle", type=click.Path(exists=True, file_okay=False, path_type=Path))
19
+ @click.option("--out", required=True, type=click.Path(path_type=Path), help="Where to write the wrapped bundle.")
20
+ @click.option("--agent", "agents", multiple=True,
21
+ help="An agent to wrap, by agent_name; repeat it for several (default: the one the tasks prompt).")
22
+ @click.option("--keep-builtins", is_flag=True, help="Keep the wrapped agents' built-in tools.")
23
+ @click.option("--no-note", is_flag=True, help="Leave the agents' instructions as they are.")
24
+ @click.option("--no-call-log", is_flag=True, help="Don't copy the agents' shell lines and tool calls into the run.")
25
+ @click.option("--build", is_flag=True, help="Build the agentvfs image from the bundle instead of pulling it.")
26
+ @click.option("--for-agent", default=None,
27
+ help="The agent the run will use (as `agent-env run --agent` names it), when not the task's own; it "
28
+ "decides whether the agent's built-in tools can be turned off.")
29
+ def wrap(bundle: Path, out: Path, agents: tuple[str, ...], keep_builtins: bool, no_note: bool, no_call_log: bool,
30
+ build: bool, for_agent: str | None) -> None:
31
+ """Copy BUNDLE to --out with its agents (by default the one each task prompts) working through agentvfs."""
32
+ try:
33
+ changes = wrap_bundle(bundle, out, list(agents) or None, keep_builtins, not no_note, not no_call_log, build, for_agent)
34
+ except WrapError as e:
35
+ raise click.ClickException(str(e)) from e
36
+ for c in changes:
37
+ click.echo(json.dumps(c))
38
+ click.echo(f"Wrote {out}; run it with: agent-env run {out}")
39
+
40
+
41
+ @vfs.command("add-env")
42
+ @click.argument("bundle", type=click.Path(exists=True, file_okay=False, path_type=Path))
43
+ @click.option("--build", is_flag=True, help="Build the agentvfs image from the bundle instead of pulling it.")
44
+ def add(bundle: Path, build: bool) -> None:
45
+ """Add the agentvfs env (envs/agentvfs) to BUNDLE, for tasks you wire up yourself."""
46
+ click.echo(f"Wrote {add_env(bundle, build)}")
agentenv_vfs/env.py ADDED
@@ -0,0 +1,72 @@
1
+ """The ``agentvfs`` env type: an MCP server env (its server in ``server/``) that fronts another env of the same run.
2
+
3
+ A deploy_env names the env it fronts (or a list of them), and optionally the role whose workspace opens at once:
4
+
5
+ {"type": "deploy_env", "env_id": "agentvfs", "env_params": {"env": "notes", "role": "alice"}}
6
+ {"type": "deploy_env", "env_id": "agentvfs", "env_params": {"env": ["notes", "crm"]}}
7
+
8
+ Once deployed, it is handed each fronted env's MCP endpoint, as its own sandbox reaches it, over ``data/add``.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from typing import ClassVar, Optional
13
+
14
+ from agent_env.attribution import Attribution
15
+ from agent_env.env.env import DeployedEnv
16
+ from agent_env.env.envs.mcp_server import MCPServerEnv
17
+ from agent_env.env.gateway import GatewayMode
18
+ from agent_env.providers.sandbox_providers.sandbox_provider import reachable_url
19
+ from agentenv_protocol import DataPart
20
+ from agentenv_protocol import client as protocol
21
+
22
+ PARAMS = ("env", "role", "headers")
23
+
24
+
25
+ class AgentVfsEnv(MCPServerEnv):
26
+ type: ClassVar[str] = "agentvfs"
27
+ description = "Another env's MCP tools as shell commands in a Mirage workspace (agentenv-vfs)"
28
+
29
+ def deploy_refusal(self, *, sandbox_type: Optional[str] = None, env_params: Optional[dict] = None,
30
+ **options) -> Optional[str]:
31
+ names = env_params.get("env") if isinstance(env_params, dict) else None
32
+ if not (isinstance(names, str) or (isinstance(names, list) and names and all(isinstance(n, str) for n in names))):
33
+ return 'agentvfs envs take env_params {"env": <the env id it fronts, or a list of them>, "role"?, "headers"?}'
34
+ if unknown := sorted(set(env_params) - set(PARAMS)):
35
+ return f"agentvfs env_params take {', '.join(PARAMS)}, not {', '.join(unknown)}"
36
+ return super().deploy_refusal(sandbox_type=sandbox_type, **options)
37
+
38
+ async def run_env_params(self, env_params: Optional[dict], deployed_envs: list[DeployedEnv]) -> Optional[dict]:
39
+ """Each fronted env's deployment, found among the run's by its id (a bundle's ids end in ``/<name>``)."""
40
+ names = env_params["env"] if isinstance(env_params["env"], list) else [env_params["env"]]
41
+ fronted = []
42
+ for name in names:
43
+ found = [d for d in deployed_envs if d.env_id == name or d.env_id.endswith(f"/{name}")]
44
+ if len(found) != 1:
45
+ raise ValueError(f"agentvfs: {len(found)} deployed envs match '{name}'; deploy it first, once")
46
+ if not found[0].mcp_url:
47
+ raise ValueError(f"agentvfs: env '{name}' serves no MCP endpoint")
48
+ fronted.append({"name": name, "mcp_url": found[0].mcp_url,
49
+ "sandbox_type": getattr(found[0], "sandbox_type", None)})
50
+ return {**env_params, "fronted": fronted}
51
+
52
+ # MCPServerEnv.deploy's own signature, whose defaults deploy_env reads, plus env_params.
53
+ async def deploy(self, ttl_seconds: int = 10800, disk_size_gb: float = 10,
54
+ gateway_mode: GatewayMode = GatewayMode.PERFORMANCE, cpu: float | None = None,
55
+ memory_mb: int | None = None, sandbox_type: str | None = None, env_state_type: str | None = None,
56
+ env_state_instance_id: str | None = None, artifact_id: str | None = None,
57
+ artifact_version: int | None = None, *, attribution: Optional[Attribution] = None,
58
+ env_params: Optional[dict] = None) -> DeployedEnv:
59
+ deployed = await super().deploy(
60
+ ttl_seconds=ttl_seconds, disk_size_gb=disk_size_gb, gateway_mode=gateway_mode, cpu=cpu,
61
+ memory_mb=memory_mb, sandbox_type=sandbox_type, env_state_type=env_state_type,
62
+ env_state_instance_id=env_state_instance_id, artifact_id=artifact_id, artifact_version=artifact_version,
63
+ attribution=attribution)
64
+ if env_params:
65
+ # Each fronted env's MCP endpoint as this env's sandbox reaches it.
66
+ envs = [{"name": f["name"], "mcp_url": reachable_url(f["mcp_url"], from_sandbox_type=f["sandbox_type"],
67
+ to_sandbox_type=getattr(deployed, "sandbox_type", None))}
68
+ for f in env_params["fronted"]]
69
+ data = {"envs": envs, **{k: env_params[k] for k in ("role", "headers") if env_params.get(k)}}
70
+ await protocol.add_data(deployed.environment_url, [DataPart(data=data)], timeout=600,
71
+ headers=deployed.control_headers)
72
+ return deployed
@@ -0,0 +1,3 @@
1
+ node_modules
2
+ *.log
3
+ __pycache__
@@ -0,0 +1,14 @@
1
+ # agentenv-vfs: an agent-env env server (Python) driving a Mirage daemon (Node 24, Mirage's published npm packages).
2
+ FROM node:24.15-bookworm-slim AS node
3
+ FROM python:3.12-slim
4
+ COPY --from=node /usr/local/bin/node /usr/local/bin/node
5
+ COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules
6
+ RUN ln -s /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm
7
+ WORKDIR /opt/agentenv-vfs
8
+ COPY package.json package-lock.json ./
9
+ RUN npm ci --omit=dev --no-audit --no-fund --loglevel=error
10
+ RUN pip install --no-cache-dir 'agentenv-framework-protocol[agent]>=0.1.652,<0.2' 'httpx>=0.27'
11
+ COPY server.py listing.py preload.ts cli.ts ./
12
+ ENV AGENTENV_VFS_HOME=/opt/agentenv-vfs MCP_PORT=18765
13
+ EXPOSE 18765
14
+ CMD ["python", "/opt/agentenv-vfs/server.py"]
@@ -0,0 +1,219 @@
1
+ /**
2
+ * One Mirage CLI per tool, named as the tool is (`send_message`), each JSON-schema parameter a flag of the same name
3
+ * (`--channel_id`, with `--channel-id` as an alias). Adapted from agentvfs/vfs-bench's workspace/cli.ts (MIT), which
4
+ * nests `<server> <tool>`; here a command is the tool's own name, so text that names a tool names its command.
5
+ *
6
+ * Parameter types map to flags as:
7
+ * - string, integer, number: a value
8
+ * - boolean: `--flag true|false`
9
+ * - array of scalars: a repeatable flag, or one JSON array (`--ids '["a","b"]'`)
10
+ * - anything else (objects, arrays of objects): one JSON value
11
+ *
12
+ * Values go loose, as a model's tool call reaches the server: the server checks them, as it does over MCP.
13
+ */
14
+ import { Argument, CLI, CLIHandler, CommandSpec, type CommandFnResult, type Context, FlagView, IOResult, z } from '@struktoai/mirage-node'
15
+ import type { NOOPAccessor } from '@struktoai/mirage-core/accessor/base'
16
+
17
+ export interface JsonSchema {
18
+ type?: string | string[]
19
+ description?: string
20
+ enum?: unknown[]
21
+ items?: JsonSchema
22
+ properties?: Record<string, JsonSchema>
23
+ required?: string[]
24
+ anyOf?: JsonSchema[]
25
+ oneOf?: JsonSchema[]
26
+ default?: unknown
27
+ nullable?: boolean
28
+ }
29
+
30
+ export interface Tool {
31
+ name: string
32
+ description?: string
33
+ parameters?: JsonSchema
34
+ }
35
+
36
+ // Where a call goes (the env server's bridge) and the role it is made as.
37
+ const ConfigSchema = z.strictObject({
38
+ url: z.string(),
39
+ role: z.string(),
40
+ })
41
+ export type Config = z.infer<typeof ConfigSchema>
42
+
43
+ const encoder = new TextEncoder()
44
+
45
+ type Kind = 'str' | 'int' | 'float' | 'bool' | 'list' | 'json'
46
+
47
+ function concrete(schema: JsonSchema): JsonSchema {
48
+ const union = schema.anyOf ?? schema.oneOf
49
+ if (union !== undefined) {
50
+ const real = union.filter((s) => s.type !== 'null')
51
+ if (real.length === 1) return { ...concrete(real[0]!), description: schema.description ?? real[0]!.description }
52
+ return { ...schema, type: 'object' }
53
+ }
54
+ if (Array.isArray(schema.type)) {
55
+ const real = schema.type.filter((t) => t !== 'null')
56
+ return { ...schema, type: real.length === 1 ? real[0] : 'object' }
57
+ }
58
+ return schema
59
+ }
60
+
61
+ function kindOf(schema: JsonSchema): Kind {
62
+ switch (schema.type) {
63
+ case 'string':
64
+ return 'str'
65
+ case 'integer':
66
+ return 'int'
67
+ case 'number':
68
+ return 'float'
69
+ case 'boolean':
70
+ return 'bool'
71
+ case 'array': {
72
+ const item = schema.items === undefined ? 'str' : kindOf(concrete(schema.items))
73
+ return item === 'str' || item === 'int' || item === 'float' ? 'list' : 'json'
74
+ }
75
+ case undefined:
76
+ return schema.enum !== undefined ? 'str' : 'json'
77
+ default:
78
+ return 'json'
79
+ }
80
+ }
81
+
82
+ /** A JSON value's shape, compactly: `[{description: string, amount?: number}]`. */
83
+ export function shape(raw: JsonSchema, depth = 0): string {
84
+ const schema = concrete(raw)
85
+ if (depth > 4) return 'any'
86
+ if (schema.enum !== undefined) return schema.enum.map((v) => JSON.stringify(v)).join('|')
87
+ switch (schema.type) {
88
+ case 'array':
89
+ return `[${schema.items === undefined ? 'any' : shape(schema.items, depth + 1)}]`
90
+ case 'object':
91
+ case undefined: {
92
+ if (schema.properties === undefined) return schema.type === undefined ? 'any' : 'object'
93
+ const need = new Set(schema.required ?? [])
94
+ const fields = Object.entries(schema.properties).map(([k, v]) => `${k}${need.has(k) ? '' : '?'}: ${shape(v, depth + 1)}`)
95
+ return `{${fields.join(', ')}}`
96
+ }
97
+ default:
98
+ return String(schema.type)
99
+ }
100
+ }
101
+
102
+ interface Param {
103
+ name: string
104
+ key: string
105
+ kind: Kind
106
+ item: Kind
107
+ }
108
+
109
+ function nullable(schema: JsonSchema): boolean {
110
+ const union = schema.anyOf ?? schema.oneOf ?? []
111
+ return schema.nullable === true || union.some((s) => s.type === 'null') || (Array.isArray(schema.type) && schema.type.includes('null'))
112
+ }
113
+
114
+ /** A flag's names: the parameter's own, and its dashed spelling when that differs. */
115
+ function namesOf(param: string): string[] {
116
+ const dashed = param.replace(/_/g, '-')
117
+ return dashed === param ? [`--${param}`] : [`--${param}`, `--${dashed}`]
118
+ }
119
+
120
+ function argumentFor(name: string, raw: JsonSchema, listed: boolean): [Argument, Param] {
121
+ const schema = concrete(raw)
122
+ const kind = kindOf(schema)
123
+ const needed = listed && raw.default === undefined && !nullable(raw)
124
+ const item = kind === 'list' ? kindOf(concrete(schema.items ?? {})) : kind
125
+ const help = [
126
+ schema.description,
127
+ kind === 'json' ? shape(schema) : '',
128
+ schema.default !== undefined ? `default ${JSON.stringify(schema.default)}` : '',
129
+ schema.enum !== undefined ? `one of ${schema.enum.map(String).join(', ')}` : '',
130
+ needed ? 'required' : '',
131
+ ]
132
+ .filter(Boolean)
133
+ .join('; ')
134
+ const init: ConstructorParameters<typeof Argument>[1] = { required: false, help: help === '' ? null : help }
135
+ if (kind === 'list') init.action = 'append'
136
+ else if (kind === 'json') init.metavar = 'JSON'
137
+ const argument = new Argument(namesOf(name), init)
138
+ return [argument, { name, key: name.replace(/-/g, '_'), kind, item }]
139
+ }
140
+
141
+ /** A flag's value as the schema's type where it reads as one, else as it is. */
142
+ function loose(text: string, kind: Kind): unknown {
143
+ if (kind === 'int') return /^[+-]?\d+$/.test(text.trim()) ? Number(text) : text
144
+ if (kind === 'float') return text.trim() !== '' && Number.isFinite(Number(text)) ? Number(text) : text
145
+ if (kind === 'bool') return text === 'true' ? true : text === 'false' ? false : text
146
+ if (kind === 'json') {
147
+ try {
148
+ return JSON.parse(text)
149
+ } catch {
150
+ return text
151
+ }
152
+ }
153
+ return text
154
+ }
155
+
156
+ function jsonArray(text: string): unknown[] | undefined {
157
+ if (!text.trimStart().startsWith('[')) return undefined
158
+ try {
159
+ const value: unknown = JSON.parse(text)
160
+ return Array.isArray(value) ? value : undefined
161
+ } catch {
162
+ return undefined
163
+ }
164
+ }
165
+
166
+ function argumentsFrom(params: Param[], ctx: Context): Record<string, unknown> {
167
+ const flags = new FlagView(ctx.flags, ctx.spec)
168
+ const out: Record<string, unknown> = {}
169
+ for (const p of params) {
170
+ if (!(p.key in (ctx.flags ?? {}))) continue
171
+ if (p.kind === 'list') {
172
+ const values = flags.asList(p.key)
173
+ const array = values.length === 1 ? jsonArray(values[0]!) : undefined
174
+ out[p.name] = array ?? values.map((v) => loose(v, p.item))
175
+ } else if (p.kind === 'str') out[p.name] = flags.asStr(p.key)
176
+ else out[p.name] = loose(flags.asStr(p.key) ?? '', p.kind)
177
+ }
178
+ return out
179
+ }
180
+
181
+ function render(result: unknown): string {
182
+ const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2)
183
+ return text.endsWith('\n') ? text : `${text}\n`
184
+ }
185
+
186
+ export interface Reply {
187
+ ok: boolean
188
+ result?: unknown
189
+ error?: string
190
+ }
191
+
192
+ export type Send = (tool: Tool, args: Record<string, unknown>, config: Config) => Promise<Reply>
193
+
194
+ /** The CLI for one tool: a root command under the tool's name whose flags are its parameters. */
195
+ export function toolCli(tool: Tool, send: Send): CLI {
196
+ const props = tool.parameters?.properties ?? {}
197
+ const required = new Set(tool.parameters?.required ?? [])
198
+ const pairs = Object.entries(props).map(([param, schema]) => argumentFor(param, schema, required.has(param)))
199
+ const params = pairs.map(([, p]) => p)
200
+ const handler = new CLIHandler({
201
+ fn: async (accessor: NOOPAccessor, _paths, _texts, ctx: Context): Promise<CommandFnResult> => {
202
+ let args: Record<string, unknown>
203
+ try {
204
+ args = argumentsFrom(params, ctx)
205
+ } catch (error) {
206
+ return [null, new IOResult({ exitCode: 2, stderr: encoder.encode(`${(error as Error).message}\n`) })]
207
+ }
208
+ const reply = await send(tool, args, accessor.config as Config)
209
+ if (!reply.ok) return [null, new IOResult({ exitCode: 1, stderr: encoder.encode(render(reply.error ?? 'failed')) })]
210
+ return [encoder.encode(render(reply.result)), new IOResult()]
211
+ },
212
+ write: true,
213
+ })
214
+ return new CLI({
215
+ spec: new CommandSpec({ name: tool.name, description: tool.description ?? null, arguments: pairs.map(([a]) => a) }),
216
+ handlers: { '': handler },
217
+ configModel: ConfigSchema,
218
+ })
219
+ }
@@ -0,0 +1,31 @@
1
+ """Tools as the shell commands that carry them, one usage line each (`<tool> --flag <type> [--opt <type>]`: what it
2
+ does), in the format of agentvfs/vfs-bench's tool listings."""
3
+
4
+ HEADER = ("Each tool is a shell command, `<tool> [--flag value ...]`, whose output is the tool's reply; a list or an "
5
+ "object is one JSON value (`--ids '[\"a\",\"b\"]'`), and `<tool> --help` says more.")
6
+
7
+
8
+ def _kind(schema: dict) -> str:
9
+ kind = schema.get("type")
10
+ if kind is None and ("anyOf" in schema or "oneOf" in schema):
11
+ kinds = [s.get("type") for s in schema.get("anyOf") or schema.get("oneOf") if s.get("type") != "null"]
12
+ kind = kinds[0] if len(kinds) == 1 else "object"
13
+ if isinstance(kind, list):
14
+ real = [k for k in kind if k != "null"]
15
+ kind = real[0] if len(real) == 1 else "object"
16
+ return "JSON" if kind in ("array", "object", None) else kind
17
+
18
+
19
+ def usage(tool: dict) -> str:
20
+ params = (tool.get("parameters") or {}).get("properties") or {}
21
+ required = set((tool.get("parameters") or {}).get("required") or [])
22
+ flags = [f"--{p} <{_kind(s)}>" if p in required else f"[--{p} <{_kind(s)}>]" for p, s in params.items()]
23
+ return " ".join([tool["name"], *flags])
24
+
25
+
26
+ def listing(tools: list[dict]) -> str:
27
+ lines = [HEADER, ""]
28
+ for t in tools:
29
+ description = " ".join((t.get("description") or "").split())
30
+ lines.append(f"- `{usage(t)}`: {description}".rstrip(": "))
31
+ return "\n".join(lines) + "\n"