@ancha-labs/cli 0.4.22 → 0.4.23
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/lib/ancha.mjs +1202 -476
- package/lib/assets/docs/apps.md +36 -0
- package/lib/assets/docs/cloud.md +30 -0
- package/lib/assets/docs/run.md +14 -0
- package/lib/assets/docs/tools.md +40 -1
- package/lib/assets/harbor/companion.mjs +155 -19
- package/lib/assets/ui/app.js +70 -11
- package/lib/mcp-entry.mjs +21 -3
- package/lib/worker.mjs +398 -79
- package/lib/world-server.mjs +95 -17
- package/package.json +1 -1
package/lib/assets/docs/apps.md
CHANGED
|
@@ -2,6 +2,42 @@
|
|
|
2
2
|
|
|
3
3
|
Use this when the AI feature lives inside an app (a web app, an API server and its workers) rather than in one command. `ancha run` starts the app once per trial against a fresh world. The world drives it: people send mail and messages, the app's own scheduled routes are called, and time passes. The checks read the world's end state and the calls the app made.
|
|
4
4
|
|
|
5
|
+
## Slack Bolt apps
|
|
6
|
+
|
|
7
|
+
`ancha init` detects Python `slack_bolt` and JavaScript `@slack/bolt` apps and writes their command and Slack transport. `ancha agent upload` installs the app and checks its connection. `ancha run --on cloud` starts it in a fresh machine for each attempt; `ancha run --on local` uses the same tests on this computer. The app runs until the trial ends, then Ancha stops it and grades the world.
|
|
8
|
+
|
|
9
|
+
For Socket Mode:
|
|
10
|
+
|
|
11
|
+
```yaml
|
|
12
|
+
agent:
|
|
13
|
+
command: python app.py
|
|
14
|
+
slack_transport: socket
|
|
15
|
+
env:
|
|
16
|
+
SLACK_APP_TOKEN: "{{slack.app_token}}"
|
|
17
|
+
SLACK_BOT_TOKEN: "{{slack.token}}"
|
|
18
|
+
SLACK_API_URL: "{{slack.url}}"
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Point both the Bolt Web API client and its Socket Mode client's API URL at `SLACK_API_URL`; `ancha connect slack` prints SDK settings. The connection check passes when the app opens its WebSocket. Each test's Slack trigger arrives as a native Slack event, including its Socket Mode envelope and acknowledgement.
|
|
22
|
+
|
|
23
|
+
For the HTTP Events API:
|
|
24
|
+
|
|
25
|
+
```yaml
|
|
26
|
+
agent:
|
|
27
|
+
command: node app.mjs
|
|
28
|
+
slack_transport: http
|
|
29
|
+
url: "http://127.0.0.1:{{agent.port}}/slack/events"
|
|
30
|
+
env:
|
|
31
|
+
PORT: "{{agent.port}}"
|
|
32
|
+
SLACK_SIGNING_SECRET: "{{slack.signing_secret}}"
|
|
33
|
+
SLACK_BOT_TOKEN: "{{slack.token}}"
|
|
34
|
+
SLACK_API_URL: "{{slack.url}}"
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The app reads `PORT` when it starts. An app with a fixed port uses that port in `agent.url`, for example `http://127.0.0.1:3000/slack/events`, with `parallel: 1` for local trials. The events URL answers Slack's signed URL verification challenge before the test starts. Keep Bolt's signature verification enabled and map the variable names your app reads under `agent.env`.
|
|
38
|
+
|
|
39
|
+
`ancha agent upload` reports the connection result and configuration to check when the app needs its app token, signing secret or port. Cloud apps use a loopback events URL and a launch command. `agent.start` remains available for existing app configurations with a health route.
|
|
40
|
+
|
|
5
41
|
## ancha.yaml
|
|
6
42
|
|
|
7
43
|
```yaml
|
package/lib/assets/docs/cloud.md
CHANGED
|
@@ -127,6 +127,8 @@ A run on this computer stays in `.ancha/runs/`; `ancha run --on local --upload`
|
|
|
127
127
|
|
|
128
128
|
## Secrets
|
|
129
129
|
|
|
130
|
+
The Agent page shows **Code**, the project's Git repository, and **Model key**, the provider key names stored in the workspace or configured under `agent.env`. Key values stay private. With no model key, it shows `ancha secrets set OPENAI_API_KEY`.
|
|
131
|
+
|
|
130
132
|
The agent's own keys, its model provider's for one, live in the workspace:
|
|
131
133
|
|
|
132
134
|
```sh
|
|
@@ -165,3 +167,31 @@ In a cloud run, the people in a world use the workspace's model credit. On this
|
|
|
165
167
|
- `AUTH_INVALID` (exit 2): the server rejected or needs an API key. Run `ancha login` again, or set `ANCHA_API_KEY` to a key from https://app.ancha.io/account. The hosted control API answers 401 to any request without a valid key.
|
|
166
168
|
- `CONFIG_INVALID` (exit 2) naming a workspace secret: the agent needs a key the workspace lacks. Run the `ancha secrets set` command in the hint.
|
|
167
169
|
- `SERVER_UNREACHABLE` (exit 3): DNS, connection or timeout failure, or an address that isn't an Ancha server. Check `--server-url` or `ANCHA_SERVER_URL`; `ancha whoami` shows the saved server.
|
|
170
|
+
|
|
171
|
+
## Run stored inputs again
|
|
172
|
+
|
|
173
|
+
```sh
|
|
174
|
+
ancha runs again <run id>
|
|
175
|
+
ancha runs again <run id> --failed --attempts 5
|
|
176
|
+
ancha runs again <run id> --detach --json
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
`runs again` starts a new cloud run from a finished run's stored project bundle, tests and options; name the run by its number (`42`) or its `run_cloud_…` ID. `--failed` selects tests with a failed, invalid or ungraded attempt. `--attempts` sets the number of attempts per selected test. The command follows the new run to its result; `--detach` returns its id and result link immediately. Use `--idempotency-key <key>` to retry the same submission safely.
|
|
180
|
+
|
|
181
|
+
In the console, **Run again** and **Rerun failed** start these same runs. **Run x5** on a test runs five attempts using the bundle from its latest cloud run for that agent. The new run's Details link back to its source. Each run uses the workspace's usual cloud hours and concurrency settings.
|
|
182
|
+
|
|
183
|
+
When the page asks for the project, run `ancha run --on cloud` from that project to upload its inputs and start a run.
|
|
184
|
+
|
|
185
|
+
## Run numbers and Started by
|
|
186
|
+
|
|
187
|
+
Workspace runs have a stable number such as `#412`. The Runs list, run title and recent runs use the same number. Open `/runs/412` in your workspace, or read it from the CLI:
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
ancha runs list
|
|
191
|
+
ancha runs show 412
|
|
192
|
+
ancha runs show '#412' --json
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
The JSON keeps the full run id alongside `runNumber`. A retry with the same idempotency key and a repeated upload keep the run's number. Historical runs keep their short ids.
|
|
196
|
+
|
|
197
|
+
**Started by** shows the signed-in person's email for console submissions, or the API key owner's email with **CLI**. In GitHub Actions, the CLI records **GitHub Actions**, the repository and a link to the workflow run from `GITHUB_ACTIONS`, `GITHUB_REPOSITORY`, `GITHUB_RUN_ID` and `GITHUB_SERVER_URL`.
|
package/lib/assets/docs/run.md
CHANGED
|
@@ -98,3 +98,17 @@ ancha world down --env <envId>
|
|
|
98
98
|
Check `ancha twins coverage <tool>` and `ancha connect <tool>`. Keep provider keys out of tests and saved configuration.
|
|
99
99
|
|
|
100
100
|
For managed `runs start`, invalid harness captures exit 3, failed/skipped/incomplete grading exits 1, and a stopped run exits 2. The grade line uses requested attempts and names invalid/skipped counts.
|
|
101
|
+
|
|
102
|
+
## Run numbers and Started by
|
|
103
|
+
|
|
104
|
+
Workspace runs have a stable number such as `#412`. The Runs list, run title and recent runs use the same number. Open `/runs/412` in your workspace, or read it from the CLI:
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
ancha runs list
|
|
108
|
+
ancha runs show 412
|
|
109
|
+
ancha runs show '#412' --json
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The JSON keeps the full run id alongside `runNumber`. A retry with the same idempotency key and a repeated upload keep the run's number. Historical runs keep their short ids.
|
|
113
|
+
|
|
114
|
+
**Started by** shows the signed-in person's email for console submissions, or the API key owner's email with **CLI**. In GitHub Actions, the CLI records **GitHub Actions**, the repository and a link to the workflow run from `GITHUB_ACTIONS`, `GITHUB_REPOSITORY`, `GITHUB_RUN_ID` and `GITHUB_SERVER_URL`.
|
package/lib/assets/docs/tools.md
CHANGED
|
@@ -1,4 +1,43 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Function tools
|
|
2
|
+
|
|
3
|
+
Run `ancha init` to find function tools in your Python or JavaScript project. It prints their names and a wiring step, and writes that step into the project's `AGENTS.md`.
|
|
4
|
+
|
|
5
|
+
Wrap the final collection you pass to the framework. Python functions, LangChain tools and OpenAI Agents SDK function tools use:
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
import ancha
|
|
9
|
+
|
|
10
|
+
tools = ancha.wrap_tools([write_email, schedule_meeting, check_calendar_availability])
|
|
11
|
+
# Pass tools to bind_tools, create_react_agent, or Agent(tools=tools).
|
|
12
|
+
# run is your task entrypoint and receives a dict containing task.
|
|
13
|
+
ancha.entry(run)
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
JavaScript functions, LangChain tools and OpenAI Agents SDK tools use:
|
|
17
|
+
|
|
18
|
+
```javascript
|
|
19
|
+
import { wrapTools, entry } from '@ancha-labs/tools';
|
|
20
|
+
|
|
21
|
+
const tools = wrapTools([write_email, schedule_meeting, check_calendar_availability]);
|
|
22
|
+
// Pass tools to your framework. run receives an object containing task.
|
|
23
|
+
await entry(run);
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
For the AI SDK, keep the named object: `const tools = wrapTools({ write_email, schedule_meeting, check_calendar_availability });` and pass it to `generateText({ model, tools, ... })`. Python's `@ancha.tool` and JavaScript's `wrapTool(name, fn)` also register individual functions. Choose one wrapping point for each function.
|
|
27
|
+
|
|
28
|
+
`entry` finishes tool registration before handing the task to your agent. Ancha records registration separately from calls and their completed results. `ancha doctor --on local --json` verifies registration even when the diagnostic task leaves a function unused. Each attempt captures these facts in `state.json` under `tools.observation`.
|
|
29
|
+
|
|
30
|
+
Import your orchestration checks with `ancha test import evals.json --world mail --judge never`:
|
|
31
|
+
|
|
32
|
+
```json
|
|
33
|
+
[{"question":"Reply to the email without booking a meeting","must_call":["write_email"],"must_not_call":["schedule_meeting"]}]
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Declared function names become `trace.called` and `trace.not_called` checks. Other bare names retain MCP interpretation; the import notes list the detected function names. The generated test's `function_tools` uses `unrecorded: run`, which executes your wrapped functions and records their outcomes. Configure their native clients with the attempt's Ancha connections before running. Edit the test's policies and recorded responses to replay imported production calls. A recorded `null` is a result; replay requires a recorded result or error for the selected call.
|
|
37
|
+
|
|
38
|
+
Required function checks verify wiring before grading. Complete the registration step named in an invalid attempt's diagnostic, then run the test again. Tool names detected during setup are candidates; the eval's explicit checks decide what must happen.
|
|
39
|
+
|
|
40
|
+
## Explore tools without a scenario
|
|
2
41
|
|
|
3
42
|
Run `ancha ui` in your project folder. Open **Tools**, choose **Create sandbox**, and select individual tools or an operations/revenue workspace preset. Every sandbox receives its own copy of the selected data. No scenario or pass/fail grade is required.
|
|
4
43
|
|
|
@@ -56538,10 +56538,10 @@ var EXECUTION_SUPPORT = {
|
|
|
56538
56538
|
"agent.input.per_event": sceneOnly,
|
|
56539
56539
|
"agent.input.events": localOnly,
|
|
56540
56540
|
"agent.input.http": all,
|
|
56541
|
-
"agent.endpoint": localOnly,
|
|
56541
|
+
"agent.endpoint": { ...localOnly, "cloud-vm": true },
|
|
56542
56542
|
"agent.slack_transport.feed": sceneOnly,
|
|
56543
|
-
"agent.slack_transport.http": localOnly,
|
|
56544
|
-
"agent.slack_transport.socket": localOnly,
|
|
56543
|
+
"agent.slack_transport.http": { ...localOnly, "cloud-vm": true },
|
|
56544
|
+
"agent.slack_transport.socket": { ...localOnly, "cloud-vm": true },
|
|
56545
56545
|
"agent.env": sceneOnly,
|
|
56546
56546
|
"agent.pass_env": sceneOnly,
|
|
56547
56547
|
"agent.execution": sceneOnly,
|
|
@@ -88598,6 +88598,7 @@ var fields2 = {
|
|
|
88598
88598
|
};
|
|
88599
88599
|
var TestFileSchema = external_exports.strictObject({
|
|
88600
88600
|
...fields2,
|
|
88601
|
+
function_tools: SceneSchema.shape.tools,
|
|
88601
88602
|
world: external_exports.union([WorldId, external_exports.record(external_exports.string(), external_exports.unknown())], { error: WORLD_ERROR }),
|
|
88602
88603
|
until: external_exports.unknown().optional(),
|
|
88603
88604
|
checks: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional(),
|
|
@@ -88605,6 +88606,7 @@ var TestFileSchema = external_exports.strictObject({
|
|
|
88605
88606
|
});
|
|
88606
88607
|
var TestFileDocument = external_exports.strictObject({
|
|
88607
88608
|
...fields2,
|
|
88609
|
+
function_tools: SceneSchema.shape.tools,
|
|
88608
88610
|
world: external_exports.union([WorldId, WorldBodySchema]).describe("A world file's id (ancha/worlds/<id>.yaml), or the world inline"),
|
|
88609
88611
|
until: SceneSchema.shape.until,
|
|
88610
88612
|
checks: SceneSchema.shape.checks.optional(),
|
|
@@ -89490,6 +89492,46 @@ function toolErrorText(text24) {
|
|
|
89490
89492
|
return out;
|
|
89491
89493
|
}
|
|
89492
89494
|
|
|
89495
|
+
// packages/core/src/function-tool-observation.ts
|
|
89496
|
+
var functionToolObservationSchema = external_exports.strictObject({
|
|
89497
|
+
registered: external_exports.array(external_exports.string()),
|
|
89498
|
+
complete: external_exports.boolean(),
|
|
89499
|
+
protocol_version: external_exports.number().int().nonnegative().optional(),
|
|
89500
|
+
required: external_exports.array(external_exports.string()),
|
|
89501
|
+
missing: external_exports.array(external_exports.string()),
|
|
89502
|
+
tools: external_exports.array(external_exports.strictObject({
|
|
89503
|
+
name: external_exports.string(),
|
|
89504
|
+
registered: external_exports.boolean(),
|
|
89505
|
+
called: external_exports.number().int().nonnegative(),
|
|
89506
|
+
completed: external_exports.number().int().nonnegative(),
|
|
89507
|
+
pending: external_exports.number().int().nonnegative()
|
|
89508
|
+
}))
|
|
89509
|
+
});
|
|
89510
|
+
function requiredFunctionTools(scene2) {
|
|
89511
|
+
const names5 = Object.keys(scene2.tools ?? {}).filter((name5) => !scene2.tools[name5].mcp);
|
|
89512
|
+
const patterns = [];
|
|
89513
|
+
const visit4 = (value4) => {
|
|
89514
|
+
if (!value4 || typeof value4 !== "object") return;
|
|
89515
|
+
for (const [key4, item2] of Object.entries(value4)) {
|
|
89516
|
+
if (key4 === "called" || key4 === "not_called") patterns.push(...(Array.isArray(item2) ? item2 : [item2]).filter((p2) => typeof p2 === "string"));
|
|
89517
|
+
else visit4(item2);
|
|
89518
|
+
}
|
|
89519
|
+
};
|
|
89520
|
+
for (const check3 of scene2.checks) if (scene2.pass.includes(check3.id)) visit4(check3);
|
|
89521
|
+
return names5.filter((name5) => patterns.some((pattern) => {
|
|
89522
|
+
const p2 = pattern.trim();
|
|
89523
|
+
const bare = /^([A-Za-z_][\w.-]{0,127})(?:\s+\{.*\})?$/s.exec(p2);
|
|
89524
|
+
const [method2, path4] = p2.split(/\s+/);
|
|
89525
|
+
return p2 === "*" || bare?.[1] === name5 || (method2 === "POST" || method2 === "*") && (path4 === `/tools/${name5}` || path4 === "/tools/*");
|
|
89526
|
+
})).sort();
|
|
89527
|
+
}
|
|
89528
|
+
function functionWiringMessage(missing7) {
|
|
89529
|
+
return `Connect function tools: ${missing7.join(", ")}. Python: import ancha; pass ancha.wrap_tools([...]) to the framework and call ancha.entry(run). JavaScript: import { wrapTools, entry } from '@ancha-labs/tools'; pass wrapTools([...]) to the framework and call await entry(run). Register tools before the task starts.`;
|
|
89530
|
+
}
|
|
89531
|
+
function functionToolWiringIssues(observation) {
|
|
89532
|
+
return observation.missing.length ? [{ kind: "tools", owner: "harness", service: "tools", message: functionWiringMessage(observation.missing) }] : [];
|
|
89533
|
+
}
|
|
89534
|
+
|
|
89493
89535
|
// packages/server/src/store.ts
|
|
89494
89536
|
import Database from "better-sqlite3";
|
|
89495
89537
|
var SCHEMA = `
|
|
@@ -101038,6 +101080,13 @@ function decide(ctx, name5, args) {
|
|
|
101038
101080
|
ctx.store.db.prepare("INSERT INTO agent_tool_calls (key, n) VALUES (?, 1) ON CONFLICT(key) DO UPDATE SET n=n+1").run(callKey);
|
|
101039
101081
|
const policy = tool?.unrecorded ?? (tool?.write ? "fail" : "simulate");
|
|
101040
101082
|
const reached = Number(getState(ctx, "reached") ?? 0);
|
|
101083
|
+
let selected2 = Math.min(n2, same3.length - 1);
|
|
101084
|
+
for (let i = same3.length - 1; i > selected2; i--) if (same3[i].atMs <= reached) {
|
|
101085
|
+
selected2 = i;
|
|
101086
|
+
break;
|
|
101087
|
+
}
|
|
101088
|
+
const observation = same3[selected2];
|
|
101089
|
+
if (observation && observation.result === void 0 && observation.error === void 0) return { source: "failed", error: `Recorded call to ${name5} needs a result or error. Capture its outcome and import the trace again.` };
|
|
101041
101090
|
const simulationKey = `${callKey} revision:${getState(ctx, "revision") ?? "0"}${tool?.schema ? ` schema:${schemaFingerprint(tool.schema)}` : ""}`;
|
|
101042
101091
|
if (policy === "run" && (tool?.write || getState(ctx, "run:changed") !== void 0 || n2 >= same3.length || same3[n2].atMs >= productionFirstWrite(ctx))) {
|
|
101043
101092
|
if (tool?.write) {
|
|
@@ -101053,14 +101102,14 @@ function decide(ctx, name5, args) {
|
|
|
101053
101102
|
index = i;
|
|
101054
101103
|
break;
|
|
101055
101104
|
}
|
|
101056
|
-
const
|
|
101057
|
-
if (tool.write &&
|
|
101058
|
-
setState(ctx, "reached", String(Math.max(reached,
|
|
101059
|
-
return { source: "replayed", error:
|
|
101105
|
+
const observation2 = n2 < same3.length ? same3[index] : void 0;
|
|
101106
|
+
if (tool.write && observation2?.error !== void 0) {
|
|
101107
|
+
setState(ctx, "reached", String(Math.max(reached, observation2.endMs)));
|
|
101108
|
+
return { source: "replayed", error: observation2.error, ...observation2.raw !== void 0 && { raw: observation2.raw, wrap: observation2.wrap } };
|
|
101060
101109
|
}
|
|
101061
|
-
if (
|
|
101110
|
+
if (observation2) setState(ctx, "reached", String(Math.max(reached, observation2.endMs)));
|
|
101062
101111
|
if (tool.write) setState(ctx, `twin:dirty:${linked2}`, "1");
|
|
101063
|
-
return { source: "twin", passthrough: true, ...
|
|
101112
|
+
return { source: "twin", passthrough: true, ...observation2 && { recording: observation2 } };
|
|
101064
101113
|
}
|
|
101065
101114
|
const cached2 = getState(ctx, `sim:${simulationKey}`);
|
|
101066
101115
|
if (cached2 !== void 0) {
|
|
@@ -101113,7 +101162,28 @@ function noteCall(ctx, name5, args, a) {
|
|
|
101113
101162
|
setState(ctx, "calls", JSON.stringify(calls2.slice(-50)));
|
|
101114
101163
|
}
|
|
101115
101164
|
function toolsToWrap(ctx) {
|
|
101116
|
-
return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => !t.mcp && (!t.pure || t.twin !== void 0) && !t.allow_unwrapped).map(([name5]) => name5).sort();
|
|
101165
|
+
return [.../* @__PURE__ */ new Set([...requiredFunctionTools(ctx.scene), ...Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => !t.mcp && (!t.pure || t.twin !== void 0) && !t.allow_unwrapped).map(([name5]) => name5)])].sort();
|
|
101166
|
+
}
|
|
101167
|
+
function functionToolObservation(ctx) {
|
|
101168
|
+
const registered = JSON.parse(getState(ctx, "wrapped") ?? "[]");
|
|
101169
|
+
const required4 = toolsToWrap(ctx), calls2 = projectToolCalls(ctx.trace.list()).filter((e) => e.source === "agent" && e.service === "tools" && e.path.startsWith("/tools/"));
|
|
101170
|
+
const protocol = getState(ctx, "protocol");
|
|
101171
|
+
return {
|
|
101172
|
+
registered,
|
|
101173
|
+
complete: getState(ctx, "complete") === "1",
|
|
101174
|
+
...protocol !== void 0 && { protocol_version: Number(protocol) },
|
|
101175
|
+
required: required4,
|
|
101176
|
+
missing: required4.filter((name5) => !registered.includes(name5)),
|
|
101177
|
+
tools: [.../* @__PURE__ */ new Set([...Object.keys(ctx.scene.tools ?? {}), ...registered])].sort().map((name5) => {
|
|
101178
|
+
const own2 = calls2.filter((e) => decodeURIComponent(e.path.slice("/tools/".length)) === name5);
|
|
101179
|
+
const pending = own2.filter((e) => e.response?.execution_status === "unknown").length;
|
|
101180
|
+
const completed = own2.filter((e) => {
|
|
101181
|
+
const r2 = e.response;
|
|
101182
|
+
return r2?.execution_status === "succeeded" || r2?.execution_status === "failed" || !r2?.passthrough && ["replayed", "replayed-elsewhere", "simulated", "validated"].includes(String(r2?.source)) && (r2?.result !== void 0 || r2?.error !== void 0);
|
|
101183
|
+
}).length;
|
|
101184
|
+
return { name: name5, registered: registered.includes(name5), called: own2.length, completed, pending };
|
|
101185
|
+
})
|
|
101186
|
+
};
|
|
101117
101187
|
}
|
|
101118
101188
|
function registration(ctx, names5) {
|
|
101119
101189
|
const before = JSON.parse(getState(ctx, "wrapped") ?? "[]");
|
|
@@ -101146,7 +101216,7 @@ function agentToolsService() {
|
|
|
101146
101216
|
...t?.twin && { twin: t.twin },
|
|
101147
101217
|
...t?.write && { write: true }
|
|
101148
101218
|
};
|
|
101149
|
-
}), wrap: toolsToWrap(ctx) });
|
|
101219
|
+
}), wrap: toolsToWrap(ctx), observation: functionToolObservation(ctx) });
|
|
101150
101220
|
}));
|
|
101151
101221
|
app2.post("/register", bodyLimit({
|
|
101152
101222
|
maxSize: TOOL_REGISTRATION_BYTES,
|
|
@@ -101170,11 +101240,15 @@ function agentToolsService() {
|
|
|
101170
101240
|
}
|
|
101171
101241
|
for (const d of definitions3.values()) setState(c.env.ctx, `definition:${d.name}`, JSON.stringify(d));
|
|
101172
101242
|
const result = registration(c.env.ctx, [...definitions3.keys()]);
|
|
101173
|
-
if (body6.
|
|
101243
|
+
if (body6.protocol_version !== void 0) setState(c.env.ctx, "protocol", String(Math.min(body6.protocol_version, AGENT_TOOLS_PROTOCOL_VERSION)));
|
|
101244
|
+
if (body6.complete && !result.missing.length) {
|
|
101245
|
+
setState(c.env.ctx, "complete", "1");
|
|
101246
|
+
setState(c.env.ctx, "checked", "1");
|
|
101247
|
+
}
|
|
101174
101248
|
return result;
|
|
101175
101249
|
});
|
|
101176
101250
|
const protocol_version = AGENT_TOOLS_PROTOCOL_VERSION;
|
|
101177
|
-
if (body6.complete && missing7.length) return c.json({ protocol_version, error: unwrappedMessage(missing7, wrapped.length === 0), wrapped, missing: missing7, stop: true }, 409, { [SETUP_ISSUE_HEADER]: "1" });
|
|
101251
|
+
if (body6.complete && missing7.length) return c.json({ protocol_version, error: requiredFunctionTools(c.env.ctx.scene).some((name5) => missing7.includes(name5)) ? functionWiringMessage(missing7) : unwrappedMessage(missing7, wrapped.length === 0), wrapped, missing: missing7, stop: true }, 409, { [SETUP_ISSUE_HEADER]: "1" });
|
|
101178
101252
|
return c.json({ protocol_version, wrapped, missing: missing7 });
|
|
101179
101253
|
} catch (error64) {
|
|
101180
101254
|
const message8 = error64 instanceof Error ? error64.message : String(error64);
|
|
@@ -101226,9 +101300,9 @@ function agentToolsService() {
|
|
|
101226
101300
|
const body6 = await c.req.json().catch(() => ({}));
|
|
101227
101301
|
const stop = withMutation(c.env.ctx, () => {
|
|
101228
101302
|
if (getState(c.env.ctx, "checked")) return void 0;
|
|
101229
|
-
setState(c.env.ctx, "checked", "1");
|
|
101230
101303
|
const { wrapped, missing: missing7 } = registration(c.env.ctx, []);
|
|
101231
|
-
|
|
101304
|
+
if (!missing7.length) setState(c.env.ctx, "checked", "1");
|
|
101305
|
+
return missing7.length ? { error: requiredFunctionTools(c.env.ctx.scene).some((name6) => missing7.includes(name6)) ? functionWiringMessage(missing7) : unwrappedMessage(missing7, wrapped.length === 0), wrapped, missing: missing7, stop: true } : void 0;
|
|
101232
101306
|
});
|
|
101233
101307
|
if (stop) return c.json(stop, 409, { [SETUP_ISSUE_HEADER]: "1" });
|
|
101234
101308
|
const ctx = c.env.ctx, args = body6.args ?? {};
|
|
@@ -101282,7 +101356,7 @@ function agentToolsService() {
|
|
|
101282
101356
|
credentials: (ctx) => ({ token: `ancha-tools-${ctx.secrets.hex(32)}` }),
|
|
101283
101357
|
actions: {},
|
|
101284
101358
|
checks: {},
|
|
101285
|
-
dumpState: (ctx) => ({ calls: ctx.store.db.prepare("SELECT key, n FROM agent_tool_calls ORDER BY key").all(), wrapped: JSON.parse(getState(ctx, "wrapped") ?? "[]"), definitions: ctx.store.db.prepare("SELECT k, v FROM agent_tool_state WHERE k LIKE 'definition:%' ORDER BY k").all() }),
|
|
101359
|
+
dumpState: (ctx) => ({ observation: functionToolObservation(ctx), calls: ctx.store.db.prepare("SELECT key, n FROM agent_tool_calls ORDER BY key").all(), wrapped: JSON.parse(getState(ctx, "wrapped") ?? "[]"), definitions: ctx.store.db.prepare("SELECT k, v FROM agent_tool_state WHERE k LIKE 'definition:%' ORDER BY k").all() }),
|
|
101286
101360
|
coverage: []
|
|
101287
101361
|
};
|
|
101288
101362
|
}
|
|
@@ -101781,7 +101855,7 @@ var Environment = class _Environment {
|
|
|
101781
101855
|
trace,
|
|
101782
101856
|
state: state2,
|
|
101783
101857
|
simMs: this.clock.elapsedMs(),
|
|
101784
|
-
harnessIssues: collectHarnessIssues(trace, checks2),
|
|
101858
|
+
harnessIssues: [...collectHarnessIssues(trace, checks2), ...Object.keys(this.scene.tools ?? {}).length > 0 ? functionToolWiringIssues(functionToolObservation(this.ctxFor("tools"))) : []],
|
|
101785
101859
|
...people3.length && { people: people3 },
|
|
101786
101860
|
...replay && { peopleReplay: { replayed: replay.replayed, live: replay.live, divergence: replay.divergence ?? null } },
|
|
101787
101861
|
...explanations.length && { explanations },
|
|
@@ -153495,6 +153569,9 @@ var SocketDelivery = class {
|
|
|
153495
153569
|
get pendingCount() {
|
|
153496
153570
|
return this.#pending.size;
|
|
153497
153571
|
}
|
|
153572
|
+
get connected() {
|
|
153573
|
+
return this.#live() && this.#socket?.readyState === import_websocket.default.OPEN;
|
|
153574
|
+
}
|
|
153498
153575
|
isCurrent(env) {
|
|
153499
153576
|
return env === this.#env && this.#live();
|
|
153500
153577
|
}
|
|
@@ -154057,6 +154134,7 @@ var TrialSessions = class {
|
|
|
154057
154134
|
pendingJobs,
|
|
154058
154135
|
pendingBlockingJobs,
|
|
154059
154136
|
pendingDeliveries,
|
|
154137
|
+
...record9.socket && { socketConnected: record9.socket.connected },
|
|
154060
154138
|
quiet: session2.state === "running" && quietNow(env, record9.busy > 0),
|
|
154061
154139
|
nextDueMs: nextDue,
|
|
154062
154140
|
...untilMs !== void 0 && { untilMs }
|
|
@@ -172621,6 +172699,7 @@ async function startIsolationGateway(options3) {
|
|
|
172621
172699
|
if (upstream.pathname !== path4 || upstream.search || upstream.hash) throw new Error("Invalid trial session route");
|
|
172622
172700
|
sessionRoutes2.set(path4, { method: method2, upstream });
|
|
172623
172701
|
}
|
|
172702
|
+
const socketGrants = /* @__PURE__ */ new Map();
|
|
172624
172703
|
const modelHosts = new Set((options3.modelHosts ?? []).map(normalizeModelHost));
|
|
172625
172704
|
const sockets = /* @__PURE__ */ new Set();
|
|
172626
172705
|
const upstreamRequests = /* @__PURE__ */ new Set();
|
|
@@ -172678,7 +172757,9 @@ async function startIsolationGateway(options3) {
|
|
|
172678
172757
|
upstream = route12.upstream;
|
|
172679
172758
|
if (path4 === "/_ancha/context") transform3 = "context";
|
|
172680
172759
|
}
|
|
172681
|
-
|
|
172760
|
+
const socketOpen = decodeURIComponent(path4) === `/e/${env.id}/slack/api/apps.connections.open`;
|
|
172761
|
+
if (req.method === "CONNECT" || req.method === "TRACE" || req.headers.upgrade || decodeURIComponent(path4).endsWith("/apps.connections.open") && !(socketOpen && options3.slackSocket && session2)) return reject2(res, 501, "This transport is not qualified for contained execution.");
|
|
172762
|
+
if (socketOpen && options3.slackSocket && session2) transform3 = "socket";
|
|
172682
172763
|
const headers = cleanHeaders(req.headers);
|
|
172683
172764
|
headers.host = modelHost ?? new URL(exposedOrigin ?? upstream.origin).host;
|
|
172684
172765
|
delete headers["x-ancha-client-origin"];
|
|
@@ -172750,6 +172831,15 @@ async function startIsolationGateway(options3) {
|
|
|
172750
172831
|
const connection4 = mapped(exposedOrigin ?? "");
|
|
172751
172832
|
value4 = { ...value4, env: connection4.env, session: connection4.session };
|
|
172752
172833
|
}
|
|
172834
|
+
if (transform3 === "socket" && reply5.statusCode === 200 && value4?.ok === true) {
|
|
172835
|
+
const grant = new URL(value4.url);
|
|
172836
|
+
const expected = loopbackOrigin(session2.eventsUrl);
|
|
172837
|
+
if (grant.protocol !== "ws:" || grant.hostname !== expected.hostname || grant.port !== expected.port || grant.search || grant.hash || grant.username || grant.password || !/^\/_ancha\/socket\/[a-f0-9]{64}$/.test(grant.pathname)) throw new Error("Invalid socket grant");
|
|
172838
|
+
for (const [path5, old] of socketGrants) if (old.expires <= Date.now()) socketGrants.delete(path5);
|
|
172839
|
+
if (socketGrants.size >= 128) throw new Error("Too many socket grants");
|
|
172840
|
+
socketGrants.set(grant.pathname, { url: grant, expires: Date.now() + 3e4 });
|
|
172841
|
+
value4 = { ...value4, url: (exposedOrigin ?? "").replace(/^http:/, "ws:") + grant.pathname };
|
|
172842
|
+
}
|
|
172753
172843
|
const body6 = JSON.stringify(value4);
|
|
172754
172844
|
delete responseHeaders["content-encoding"];
|
|
172755
172845
|
delete responseHeaders["content-length"];
|
|
@@ -172790,7 +172880,52 @@ async function startIsolationGateway(options3) {
|
|
|
172790
172880
|
});
|
|
172791
172881
|
});
|
|
172792
172882
|
server.on("clientError", (_error, socket) => socket.destroy());
|
|
172793
|
-
server.on("upgrade", (
|
|
172883
|
+
server.on("upgrade", (req, socket, head) => {
|
|
172884
|
+
const denied = () => {
|
|
172885
|
+
socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", () => socket.destroy());
|
|
172886
|
+
};
|
|
172887
|
+
const grant = socketGrants.get(req.url ?? "");
|
|
172888
|
+
if (closed || !options3.slackSocket || !grant || grant.expires <= Date.now() || req.method !== "GET" || req.headers.upgrade?.toLowerCase() !== "websocket") {
|
|
172889
|
+
denied();
|
|
172890
|
+
return;
|
|
172891
|
+
}
|
|
172892
|
+
socketGrants.delete(req.url);
|
|
172893
|
+
const headers = { host: grant.url.host, connection: "Upgrade", upgrade: "websocket" };
|
|
172894
|
+
for (const name5 of ["sec-websocket-key", "sec-websocket-version", "sec-websocket-protocol", "sec-websocket-extensions"]) if (req.headers[name5] !== void 0) headers[name5] = req.headers[name5];
|
|
172895
|
+
const target4 = request({ hostname: grant.url.hostname, port: grant.url.port || 80, path: grant.url.pathname, headers, agent: false });
|
|
172896
|
+
upstreamRequests.add(target4);
|
|
172897
|
+
target4.once("close", () => upstreamRequests.delete(target4));
|
|
172898
|
+
target4.once("error", () => socket.destroy());
|
|
172899
|
+
target4.once("response", (reply5) => {
|
|
172900
|
+
reply5.destroy();
|
|
172901
|
+
denied();
|
|
172902
|
+
});
|
|
172903
|
+
target4.setTimeout(1e4, () => target4.destroy());
|
|
172904
|
+
socket.once("close", () => target4.destroy());
|
|
172905
|
+
target4.once("upgrade", (reply5, peer, upstreamHead) => {
|
|
172906
|
+
target4.setTimeout(0);
|
|
172907
|
+
if (closed || socket.destroyed) {
|
|
172908
|
+
peer.destroy();
|
|
172909
|
+
return;
|
|
172910
|
+
}
|
|
172911
|
+
sockets.add(peer);
|
|
172912
|
+
peer.once("close", () => {
|
|
172913
|
+
sockets.delete(peer);
|
|
172914
|
+
socket.destroy();
|
|
172915
|
+
});
|
|
172916
|
+
peer.on("error", () => socket.destroy());
|
|
172917
|
+
socket.once("close", () => peer.destroy());
|
|
172918
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r
|
|
172919
|
+
${Object.entries(reply5.headers).map(([name5, value4]) => `${name5}: ${value4}`).join("\r\n")}\r
|
|
172920
|
+
\r
|
|
172921
|
+
`);
|
|
172922
|
+
if (upstreamHead.length) socket.write(upstreamHead);
|
|
172923
|
+
if (head.length) peer.write(head);
|
|
172924
|
+
socket.pipe(peer);
|
|
172925
|
+
peer.pipe(socket);
|
|
172926
|
+
});
|
|
172927
|
+
target4.end();
|
|
172928
|
+
});
|
|
172794
172929
|
server.on("connect", (_req, client2) => client2.end("HTTP/1.1 403 Rejected\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"));
|
|
172795
172930
|
await new Promise((resolve6, rejectListen) => {
|
|
172796
172931
|
server.once("error", rejectListen);
|
|
@@ -172806,6 +172941,7 @@ async function startIsolationGateway(options3) {
|
|
|
172806
172941
|
let closing;
|
|
172807
172942
|
const close = () => closing ??= (async () => {
|
|
172808
172943
|
closed = true;
|
|
172944
|
+
socketGrants.clear();
|
|
172809
172945
|
options3.signal?.removeEventListener("abort", abort);
|
|
172810
172946
|
for (const target4 of upstreamRequests) target4.destroy();
|
|
172811
172947
|
for (const socket of sockets) socket.destroy();
|