@anyswarm/core 0.5.1 → 0.5.2
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/AGENTS.md +1 -1
- package/README.md +13 -6
- package/dist/examples/README.md +16 -5
- package/dist/examples/authoring/README.md +4 -4
- package/dist/examples/autoresearch/README.md +15 -8
- package/dist/examples/autoresearch/REQUIREMENTS.zh.md +3 -10
- package/dist/examples/autoresearch/demo.js +1 -1
- package/dist/examples/autoresearch/eject.json +2 -0
- package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -0
- package/dist/examples/autoresearch/frontiercs2-config.js +3 -0
- package/dist/examples/autoresearch/prepare-demo.d.ts +1 -0
- package/dist/examples/autoresearch/prepare-demo.js +15 -0
- package/dist/examples/autoresearch/prepare.js +3 -3
- package/dist/examples/autoresearch/project.d.ts +0 -94
- package/dist/examples/autoresearch/project.js +2 -20
- package/dist/examples/code/README.md +25 -17
- package/dist/examples/code/REQUIREMENTS.zh.md +3 -3
- package/dist/examples/harness-session/README.md +3 -3
- package/dist/examples/messages/README.md +1 -1
- package/dist/examples/notes/README.md +3 -3
- package/dist/examples/services/mathlib-search/README.md +1 -1
- package/dist/examples/services/persistent-board/README.md +5 -2
- package/dist/examples/subagents/README.md +2 -2
- package/dist/examples/subagents/config.js +3 -3
- package/dist/examples/substrate/README.md +2 -2
- package/dist/examples/super/README.md +34 -22
- package/dist/examples/super/actions.d.ts +1 -1
- package/dist/examples/super/actions.js +11 -11
- package/dist/examples/super/config.js +3 -3
- package/dist/examples/super/eject.json +1 -1
- package/dist/examples/super/location.js +1 -1
- package/dist/examples/super/operator.d.ts +1 -0
- package/dist/examples/super/operator.js +31 -0
- package/dist/examples/super/project.d.ts +0 -107
- package/dist/examples/super/project.js +1 -3
- package/dist/scripts/anyswarm-arguments.d.ts +7 -25
- package/dist/scripts/anyswarm-arguments.js +69 -97
- package/dist/scripts/anyswarm-eject.js +1 -1
- package/dist/scripts/anyswarm-harnesses.d.ts +0 -1
- package/dist/scripts/anyswarm-harnesses.js +1 -22
- package/dist/scripts/anyswarm-installation.d.ts +7 -40
- package/dist/scripts/anyswarm-installation.js +17 -291
- package/dist/scripts/anyswarm-launch.d.ts +6 -36
- package/dist/scripts/anyswarm-launch.js +32 -81
- package/dist/scripts/anyswarm-progress.d.ts +6 -0
- package/dist/scripts/anyswarm-progress.js +102 -0
- package/dist/scripts/anyswarm-project.d.ts +1 -9
- package/dist/scripts/anyswarm-project.js +40 -127
- package/dist/scripts/anyswarm-source-runner.js +9 -41
- package/dist/scripts/anyswarm.js +6 -26
- package/dist/scripts/build-provenance.json +1 -1
- package/dist/scripts/local-environment.d.ts +10 -4
- package/dist/scripts/local-environment.js +67 -20
- package/dist/scripts/local-setup.d.ts +3 -0
- package/dist/scripts/local-setup.js +135 -107
- package/dist/scripts/pack-release.js +4 -1
- package/dist/src/core/worker-image.js +1 -1
- package/dist/src/harness/project-harness.d.ts +1 -0
- package/dist/src/harness/project-harness.js +2 -2
- package/dist/src/harness/project-runtime.js +3 -1
- package/docs/INDEX.md +2 -1
- package/docs/architecture/04-services.md +1 -1
- package/docs/architecture/07-run-configuration.md +28 -14
- package/docs/architecture/12-code-coverage.md +56 -57
- package/docs/architecture/17-harness-reporting.md +1 -1
- package/docs/architecture/22-website.md +4 -7
- package/docs/architecture/23-project-harness.md +48 -23
- package/docs/architecture/26-code.md +20 -5
- package/docs/architecture/27-personal.md +23 -8
- package/docs/architecture/28-autoresearch.md +18 -6
- package/docs/architecture/INDEX.md +1 -2
- package/docs/architecture/prompts/source-manifest.json +5 -5
- package/docs/architecture/source-map.json +51 -71
- package/docs/designs/core-harness/01-core.md +2 -2
- package/docs/designs/core-harness/06-project-harness.md +3 -3
- package/docs/designs/core-harness/README.md +2 -2
- package/docs/en/agents.md +1 -1
- package/docs/en/build-your-harness.md +1 -1
- package/docs/en/changelog.md +7 -0
- package/docs/en/first-harness.md +6 -6
- package/docs/en/harnesses/lead-worker.md +1 -1
- package/docs/en/harnesses/peermesh.md +2 -2
- package/docs/en/harnesses/subagents.md +2 -2
- package/docs/en/harnesses/substrate.md +4 -4
- package/docs/en/harnesses/taskpool.md +2 -2
- package/docs/en/latest.md +9 -5
- package/docs/en/quickstart.md +20 -41
- package/docs/en/reference/api.md +1 -1
- package/docs/en/reference/cli.md +47 -85
- package/docs/en/sandbox.md +3 -3
- package/docs/operations/trace-viewer.md +1 -1
- package/docs/third-party-notices.md +0 -1
- package/docs/workflows/development.md +14 -12
- package/docs/workflows/release-and-docs-versioning.md +13 -12
- package/docs/workflows/release-cli-acceptance.md +85 -0
- package/docs/zh/agents.md +1 -1
- package/docs/zh/build-your-harness.md +1 -1
- package/docs/zh/changelog.md +8 -1
- package/docs/zh/first-harness.md +7 -7
- package/docs/zh/harnesses/lead-worker.md +1 -1
- package/docs/zh/harnesses/peermesh.md +2 -2
- package/docs/zh/harnesses/subagents.md +2 -2
- package/docs/zh/harnesses/substrate.md +4 -4
- package/docs/zh/harnesses/taskpool.md +2 -2
- package/docs/zh/latest.md +9 -5
- package/docs/zh/quickstart.md +20 -41
- package/docs/zh/reference/api.md +1 -1
- package/docs/zh/reference/cli.md +19 -79
- package/docs/zh/sandbox.md +3 -3
- package/examples/README.md +16 -5
- package/examples/authoring/README.md +4 -4
- package/examples/autoresearch/README.md +15 -8
- package/examples/autoresearch/REQUIREMENTS.zh.md +3 -10
- package/examples/autoresearch/demo.ts +1 -1
- package/examples/autoresearch/eject.json +2 -0
- package/examples/autoresearch/frontiercs2-config.ts +4 -0
- package/examples/autoresearch/prepare-demo.ts +15 -0
- package/examples/autoresearch/prepare.ts +3 -3
- package/examples/autoresearch/project.ts +2 -19
- package/examples/code/README.md +25 -17
- package/examples/code/REQUIREMENTS.zh.md +3 -3
- package/examples/harness-session/README.md +3 -3
- package/examples/messages/README.md +1 -1
- package/examples/notes/README.md +3 -3
- package/examples/services/mathlib-search/README.md +1 -1
- package/examples/services/persistent-board/README.md +5 -2
- package/examples/subagents/README.md +2 -2
- package/examples/subagents/config.ts +4 -3
- package/examples/substrate/README.md +2 -2
- package/examples/super/README.md +34 -22
- package/examples/super/actions.ts +11 -11
- package/examples/super/config.ts +3 -3
- package/examples/super/eject.json +1 -1
- package/examples/super/location.ts +1 -1
- package/examples/super/operator.ts +28 -0
- package/examples/super/project.ts +1 -3
- package/npm-shrinkwrap.development.json +42 -1541
- package/npm-shrinkwrap.json +3 -43
- package/package.development.json +2 -6
- package/package.json +2 -5
- package/scripts/anyswarm-arguments.ts +67 -96
- package/scripts/anyswarm-eject.ts +1 -1
- package/scripts/anyswarm-harnesses.ts +1 -18
- package/scripts/anyswarm-installation.ts +18 -294
- package/scripts/anyswarm-launch.ts +30 -102
- package/scripts/anyswarm-progress.ts +95 -0
- package/scripts/anyswarm-project.ts +31 -123
- package/scripts/anyswarm-source-runner.ts +9 -36
- package/scripts/anyswarm.ts +4 -24
- package/scripts/local-environment.ts +71 -20
- package/scripts/local-setup.ts +134 -94
- package/scripts/pack-release.ts +4 -1
- package/src/core/worker-image.ts +1 -1
- package/src/harness/project-harness.ts +2 -2
- package/src/harness/project-runtime.ts +2 -1
- package/dist/scripts/anyswarm-applications.d.ts +0 -19
- package/dist/scripts/anyswarm-applications.js +0 -19
- package/dist/scripts/anyswarm-tui-config.d.ts +0 -36
- package/dist/scripts/anyswarm-tui-config.js +0 -189
- package/dist/scripts/anyswarm-tui-session.d.ts +0 -66
- package/dist/scripts/anyswarm-tui-session.js +0 -304
- package/dist/scripts/anyswarm-tui-terminal.d.ts +0 -41
- package/dist/scripts/anyswarm-tui-terminal.js +0 -154
- package/dist/scripts/anyswarm-tui.d.ts +0 -2
- package/dist/scripts/anyswarm-tui.js +0 -1012
- package/docs/architecture/25-foreground-tui.md +0 -51
- package/scripts/anyswarm-applications.ts +0 -39
- package/scripts/anyswarm-tui-config.ts +0 -174
- package/scripts/anyswarm-tui-session.ts +0 -295
- package/scripts/anyswarm-tui-terminal.ts +0 -147
- package/scripts/anyswarm-tui.ts +0 -912
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
# Installed CLI and streaming terminal
|
|
2
|
-
|
|
3
|
-
The installed `anys` and `anyswarm` executables point at the same host. Bare invocation opens a terminal with a persistent composer. `-u <harness> [prompt]` selects the same interface when stdin and stdout are TTYs and TERM supports it. Otherwise the host runs headless. Bare non-TTY invocation exits with usage guidance before loading terminal code or creating state. Help and version take the short path. The fixed infrastructure commands are `setup`, `doctor`, `trace`, `recover`, `eject` and `update`.
|
|
4
|
-
|
|
5
|
-
## Loading and transports
|
|
6
|
-
|
|
7
|
-
The selector accepts a registered name, an installed package resolved with Node's ESM conditions from the invocation directory, or an explicit `.ts`, `.mts`, `.js` or `.mjs` path. The built-in registry owns aliases, module locations and default lifetimes. The common loader validates the Harness default export and reads optional named `observe`, `slashActions` and `resolveWorkspace` exports from the same module. The host reports an absent bundled application. [Code](26-code.md) uses the shared input, event and question contracts. [AutoResearch](28-autoresearch.md) uses Slash Actions to prepare and launch evaluations.
|
|
8
|
-
|
|
9
|
-
`anys run <name> [prompt]` follows the same selection path. An explicit local source path runs in a Node child for source maps, source arguments and SDK-bound exports. A normal script owns its argv and I/O. A Harness default export uses the shared TUI for interactive launch with a positional prompt or automatic mode. In a pipe the legacy no-argument task and explicit `--prompt` source routes retain their single foreground result. The legacy `--harness H --mode foreground|rpc|tui` and foreground `--prompt` routes retain their transport selection. See [Project Harness](23-project-harness.md) for source loader diagnostics and export verification.
|
|
10
|
-
|
|
11
|
-
Explicit `--headless` and generic selection without a TTY subscribe to Session events before admission. They publish JSONL state, activity and one final result to stdout. Diagnostics go to stderr. The initial prompt and workspace come from the arguments or the default prompt and invocation directory. Headless runs have no question or stdin command channel. `--rpc` uses the existing stdio Session protocol, taking the workspace and prompt from its start request. The project host bounds its output queue, coalesces only consecutive unsent state frames, and asks the Run to stop on pipe failure or an external termination signal.
|
|
12
|
-
|
|
13
|
-
A project module may export `slashActions`, an object keyed by lowercase command names without the slash. A handler receives `{args, cwd, configuration, outputRoot, signal, progress?}`. `args` is the rest of the command as text. The terminal provides a progress callback for the activity stream. `anys -u H --cmd '/action args'` writes an ordinary JSON-serializable return value to stdout and keeps diagnostics on stderr. A handler can return `{kind: 'action-report', exitCode, result}` to print the same diagnostic payload with an explicit status between 0 and 125. The composer displays that result in its stream. SIGINT or SIGTERM aborts the handler signal. A handler that allocates resources owns their cleanup.
|
|
14
|
-
|
|
15
|
-
An action can return `{kind: 'start-run', cwd, prompt, configuration?}` to launch the selected Harness. The host validates the workspace and prompt and uses the selected configuration when the action omits it. The terminal admits an owned Session, retaining its stream and Agent controls. It refuses a new Run while another is active or cleanup is pending. The standalone command uses the generic headless session and exits with its result code. Internal configuration and launch options stay in process. An optional `resolveWorkspace({cwd, configuration})` export chooses the capture directory for a normal terminal or headless selection without an explicit CLI workspace. RPC start and the direct SDK use the supplied input workspace.
|
|
16
|
-
|
|
17
|
-
An owned Harness can emit `{kind: 'trace.request', runDirectory}`. The host checks that the absolute directory ends in the active Run ID and starts a loopback Viewer scoped to that Run. The terminal prints the URL in the stream and header. The headless host writes the URL to stderr and preserves its JSONL output. Viewer launch errors are diagnostics. The host closes its server on exit and prints an `anys trace --root` replay command.
|
|
18
|
-
|
|
19
|
-
## Selecting and owning a Session
|
|
20
|
-
|
|
21
|
-
The composer can select a module with `/use H [prompt]` or the registered application shorthands. It selects configuration, validates the default export and supported lifetime, and starts a foreground Run when an initial prompt is submitted. The host subscribes before admission and passes resolved cwd, configuration, output root, question capability and lifetime to the Session. A configured positive close timeout adds five seconds for the host stop deadline. The default host limit is 35 seconds. A failed selection clears the previous launchable definition and subsequent prompts require another valid selection.
|
|
22
|
-
|
|
23
|
-
`--config` and `/config <path>` select a trusted local module. Launcher settings are refreshed for the selected Harness. An owner-only preference can be written with `/config --remember` and removed with `/config --forget`. `/config --default` selects defaults for this launch. The file is `$XDG_CONFIG_HOME/anyswarm/launcher.json` or `~/.config/anyswarm/launcher.json`. Reads reject symlinks, non-regular files, wrong owners, group/world access and files above 8 KiB. Writes use an owner-only temporary file and atomic rename. `/doctor` and `/setup-host pi|codex` reuse local diagnostics and setup. Explicit backend selection keeps platform setup independent of terminal input. The setup abort signal is delivered on exit and the host gives it up to 45 seconds to unwind.
|
|
24
|
-
|
|
25
|
-
A module can export `observe({cwd, configuration, outputRoot, signal})` and return `{session, close}` for an application-owned Session, or return `undefined` when the background host is unavailable. The terminal attempts connection on selection and subscribes to the existing Session without calling `start`. `/attach` retries connection. The application owns starting, retaining, and stopping its daemon.
|
|
26
|
-
|
|
27
|
-
When a different Harness is requested, an observer is disconnected before the next selection. An active foreground Run displays a `/y` or `/n` confirmation. On confirmation it sends a stable stop request, awaits completion and checks the cleanup receipt before loading the next Harness. Unconfirmed cleanup leaves the current Run visible. If a foreground Run has completed with confirmed cleanup, a new main prompt can admit another Run for the selected Harness. The recent stream remains in the terminal across selection and Run changes.
|
|
28
|
-
|
|
29
|
-
`/quit` waits for a foreground Run's cleanup and prints the final result, available artifact paths and report location after restoring the terminal. The report preserves the Harness result and trace references. In observer mode it disconnects, as does submitting `q`. Observer disconnection has a one-second confirmation limit. `/stop` explicitly requests stopping the Session, including an observed Session. Process signals and terminal disconnection stop owned foreground work and detach from application-owned work. Signal exits preserve the corresponding exit code.
|
|
30
|
-
|
|
31
|
-
An interactive Harness can set `business.exitCode` to 0 while idle after a successful task. The TUI also reads the same field in `business.detail` for Runtime observers. Explicit `/quit` then returns 0 when the requested foreground stop reports complete cleanup, successful required export and a saved report. The restored terminal prints `Run ended` in this case. The saved Run keeps its underlying stop reason and lifecycle outcome. Active work, failed checks, unconfirmed cleanup and failed exports retain the host's exit status.
|
|
32
|
-
|
|
33
|
-
## Rendering and input
|
|
34
|
-
|
|
35
|
-
The first status row puts the lifecycle phase before the mode and Agent counts so it stays visible when the title is clipped. The dimmed second row shows Trace status and `state.business.summary` or the workspace and available model aliases. A horizontal rule separates the status from the stream. The main view merges live message blocks, Harness activity, phase changes, receipts and input into one bounded stream. Messages use Agent or role labels. The stream shows short textual event summaries and tool names. Full tool payloads and Service inspection belong in Trace and the SDK/RPC observation interfaces. The terminal subscribes to Session updates and never polls Service state. On subscription failure it waits 250 ms and subscribes again with an initial snapshot. Gap and truncation notices distinguish the live preview from durable Run records.
|
|
36
|
-
|
|
37
|
-
The input editor sits below the stream with the current mode and selected Agent in its top border. The indented `pi-tui` Editor supports bracketed paste, Unicode input, slash completion and multiline editing. On stdout `resize`, the renderer reads the current columns and rows, rewraps the stream and editor, and reallocates the viewport without resetting the draft or Session. Under nine rows it omits the upper rule, and under seven it also omits the second status row. The editor retains its target label and cursor line in the available space. Below eight columns or five rows the screen shows only the CLI name until it grows again. The renderer follows the stream until the user scrolls with Page Up or Page Down. Ctrl+End resumes following. The terminal bounds paste to 256 KiB, strips control sequences from untrusted output and masks environment and configuration secrets. Exiting restores the original raw mode, paste mode, cursor and alternate screen even when rendering fails. It makes a bounded attempt to flush terminal restoration.
|
|
38
|
-
|
|
39
|
-
Pending `askUser` questions render inline with the source, ID, text and choices. `/y` and `/n` answer a single confirm question. `/approve [id] [comment]` and `/reject [id] [reason]` allow explicit selection when there are multiple questions. With a single confirm and no declared rejection action, `/reject <reason>` rejects that confirm. Prefix an explicit question ID with `#` to disambiguate it from a reason. Confirm answers are booleans. Optional comments and reasons are terminal context. `/reply [id] <answer>` submits text or an exact option ID. A question must still be pending, unexpired and within the answer byte limit. A matching question ID has priority over an application approval action. Otherwise a declared approval action can receive its own business identifier.
|
|
40
|
-
|
|
41
|
-
`/agents` lists members with their available controls. Up or Down highlights a member, and Enter targets its stable ID. `/target main` returns to the Harness input route. `@agent text`, `/to agent text` and a targeted composer send through `session.agents.send`. `/to agent --follow-up text` requests follow-up, and follow-up is also selected if it is the only supported text mode. `/stop agent` calls the member stop control, and Ctrl+C or `/interrupt` interrupts the selected member or a uniquely inferred target. Escape or Ctrl+C dismisses a pending switch or target selection. Capabilities and unique names or IDs are checked against the live Session. Requests use stable IDs, and `/retry [operation]` replays an unknown operation's original identity and payload. Pending requests cannot be submitted twice.
|
|
42
|
-
|
|
43
|
-
Main text during a Run goes to `session.input`. For a schema that requires non-string JSON, the composer accepts a JSON value. For an active Session, a slash input unmatched by platform commands or standalone actions is sent as the original string to the Harness input handler. `inputDescriptor.commands` can suggest slash names, including names advertised by a registered input handler. A declared `@mention` sends the original text to that handler before looking up native Agent targets. An unavailable input route reports an error. `/status` prints the Run ID, phase, Agent summary and available artifact and report paths.
|
|
44
|
-
|
|
45
|
-
`/trace [records-directory]` starts the existing Trace Viewer on an ephemeral loopback port and prints its URL in the stream. It selects the explicit path, the configured output root, the output root that contains the latest completed foreground Run, or the default state-directory Run root in that order. For an observed Session with a report, it uses the report directory in place of the foreground output root. A foreground Viewer can therefore discover later Runs saved under the same root. The terminal reuses a Viewer for the same resolved directory. A different directory starts a new Viewer before the terminal closes the previous one. Startup failures leave the existing Viewer available and print an error in the stream. The terminal closes its Viewer on exit. For events outside the bounded TUI preview, consult the [Trace Viewer guide](../operations/trace-viewer.md).
|
|
46
|
-
|
|
47
|
-
Observed applications can return a `traceRoot` with the Session. The terminal uses it for `/trace` when there is no explicit records directory or output option. The [Personal Harness](27-personal.md) uses the shared observation and Slash Action contracts.
|
|
48
|
-
|
|
49
|
-
## Verification
|
|
50
|
-
|
|
51
|
-
The command tests cover local modules, installed ESM packages, headless and legacy JSON transports, RPC and standalone actions. The Linux PTY tests exercise selection, a failed switch fence, Unicode, continuous prompts, the inline question kinds, Agent controls, foreground cleanup, and an independently live observer. A running PTY is shrunk and expanded with an inline decision and an unsent draft, then the draft is submitted. The tests also check the loopback Trace API for successive foreground Runs and after switching to an explicit Trace directory. The Board example emits two real SQLite commits without Agent allocation. SDK and RPC tests cover the independent read-only Service state and Session controls.
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import { existsSync } from 'node:fs';
|
|
2
|
-
import type { HarnessSession } from '../src/harness/project-harness.js';
|
|
3
|
-
|
|
4
|
-
export interface ApplicationObservation {
|
|
5
|
-
session: HarnessSession;
|
|
6
|
-
/** Local records owned by the observed application. */
|
|
7
|
-
traceRoot?: string;
|
|
8
|
-
/** Disconnects the observer while the application retains background ownership. */
|
|
9
|
-
close(): void | Promise<void>;
|
|
10
|
-
}
|
|
11
|
-
export interface ApplicationDescriptor {
|
|
12
|
-
id: string;
|
|
13
|
-
title: string;
|
|
14
|
-
harness: string;
|
|
15
|
-
lifetime: 'task' | 'interactive';
|
|
16
|
-
available: boolean;
|
|
17
|
-
}
|
|
18
|
-
const applications = [
|
|
19
|
-
{ id: 'code', title: 'Code', lifetime: 'interactive' },
|
|
20
|
-
{ id: 'autoresearch', title: 'AutoResearch', lifetime: 'task' },
|
|
21
|
-
{ id: 'super', title: 'Personal', lifetime: 'interactive' },
|
|
22
|
-
] as const;
|
|
23
|
-
|
|
24
|
-
export function applicationDescriptors(): readonly ApplicationDescriptor[] {
|
|
25
|
-
return applications.map(application => {
|
|
26
|
-
const entry = new URL(`../examples/${application.id}/project.js`, import.meta.url);
|
|
27
|
-
return { ...application, harness: entry.href, available: existsSync(entry) };
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function findApplication(id: string): ApplicationDescriptor | undefined {
|
|
32
|
-
return applicationDescriptors().find(application => application.id === id);
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export const applicationAliases = applications.map(application => application.id);
|
|
36
|
-
|
|
37
|
-
export function preferredTerminalLifetime(id: string) {
|
|
38
|
-
return findApplication(id)?.lifetime ?? (id === 'subagents' ? 'interactive' : undefined);
|
|
39
|
-
}
|
|
@@ -1,174 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { constants } from 'node:fs';
|
|
3
|
-
import { lstat, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';
|
|
4
|
-
import { homedir } from 'node:os';
|
|
5
|
-
import { dirname, extname, isAbsolute, join, resolve } from 'node:path';
|
|
6
|
-
import { loadAnySwarmConfig } from '../src/core/sandbox/sandbox-connection.js';
|
|
7
|
-
import { selectExecutorDriver } from '../src/core/sandbox/executor-driver.js';
|
|
8
|
-
import { builtinConfiguration, builtins } from './anyswarm-harnesses.js';
|
|
9
|
-
import { runLocalCommand } from './local-setup.js';
|
|
10
|
-
|
|
11
|
-
type Builtin = keyof typeof builtins;
|
|
12
|
-
type Budget = { key: string; max: number };
|
|
13
|
-
const timerMax = 2_147_483_647;
|
|
14
|
-
const runtimeBudgets = [
|
|
15
|
-
{ key: 'workTimeoutMs', max: timerMax },
|
|
16
|
-
{ key: 'closeTimeoutMs', max: timerMax },
|
|
17
|
-
];
|
|
18
|
-
const budgets: Record<string, readonly Budget[]> = {
|
|
19
|
-
subagents: [...runtimeBudgets, { key: 'questionTimeoutMs', max: 120_000 }],
|
|
20
|
-
taskpool: runtimeBudgets,
|
|
21
|
-
peermesh: [{ key: 'durationMs', max: 86_400_000 }],
|
|
22
|
-
substrate: [...runtimeBudgets, { key: 'turnTimeoutMs', max: timerMax }],
|
|
23
|
-
'lead-worker': [runtimeBudgets[0], { key: 'closeTimeoutMs', max: 60_000 },
|
|
24
|
-
{ key: 'turnTimeoutMs', max: timerMax }],
|
|
25
|
-
notes: [{ key: 'turnTimeoutMs', max: timerMax }, runtimeBudgets[1]],
|
|
26
|
-
messages: [{ key: 'workTimeoutMs', max: timerMax },
|
|
27
|
-
{ key: 'cleanupTimeoutMs', max: timerMax }],
|
|
28
|
-
};
|
|
29
|
-
|
|
30
|
-
function builtin(name: string): name is Builtin {
|
|
31
|
-
return Object.hasOwn(builtins, name);
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export function terminalObject(value: unknown): Record<string, unknown> {
|
|
35
|
-
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
const preferencesPath = () => resolve(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'anyswarm', 'launcher.json');
|
|
39
|
-
type ConfigurationChoice = { path?: string; source: string };
|
|
40
|
-
type Preference = { version: 1; harness: string; configPath: string };
|
|
41
|
-
|
|
42
|
-
async function readPreference(path: string): Promise<Preference | undefined> {
|
|
43
|
-
let handle;
|
|
44
|
-
try {
|
|
45
|
-
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
46
|
-
} catch (error) {
|
|
47
|
-
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
|
|
48
|
-
throw error;
|
|
49
|
-
}
|
|
50
|
-
try {
|
|
51
|
-
const file = await handle.stat();
|
|
52
|
-
if (!file.isFile() || file.size > 8192 || (file.mode & 0o077) !== 0 ||
|
|
53
|
-
(process.getuid && file.uid !== process.getuid())) throw new Error('Launcher preferences must be an owner-only file');
|
|
54
|
-
const data = Buffer.alloc(8193);
|
|
55
|
-
const { bytesRead } = await handle.read(data, 0, data.length, 0);
|
|
56
|
-
if (bytesRead > 8192) throw new Error('Launcher preferences exceed 8 KiB');
|
|
57
|
-
const pref = terminalObject(JSON.parse(data.subarray(0, bytesRead).toString('utf8')));
|
|
58
|
-
if (pref.version !== 1 || typeof pref.harness !== 'string' || typeof pref.configPath !== 'string' ||
|
|
59
|
-
!isAbsolute(pref.configPath) || Object.keys(pref).length !== 3) {
|
|
60
|
-
throw new Error('Invalid launcher preferences. Select a trusted configuration or forget the saved preference.');
|
|
61
|
-
}
|
|
62
|
-
return pref as Preference;
|
|
63
|
-
} finally { await handle.close(); }
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export class LauncherConfiguration {
|
|
67
|
-
readonly workspace: string;
|
|
68
|
-
readonly preferencePath = preferencesPath();
|
|
69
|
-
readonly isBuiltin: boolean;
|
|
70
|
-
source = 'environment';
|
|
71
|
-
path?: string;
|
|
72
|
-
preference?: Preference;
|
|
73
|
-
preferenceError?: string;
|
|
74
|
-
error?: string;
|
|
75
|
-
configuration?: Record<string, unknown>;
|
|
76
|
-
diagnostics?: Awaited<ReturnType<typeof runLocalCommand>>;
|
|
77
|
-
private choice?: ConfigurationChoice;
|
|
78
|
-
|
|
79
|
-
constructor(readonly harness: string, readonly specifier: string, readonly launchDirectory: string, cwd?: string, path?: string, choice?: ConfigurationChoice) {
|
|
80
|
-
this.workspace = resolve(launchDirectory, cwd ?? '.');
|
|
81
|
-
this.isBuiltin = builtin(specifier);
|
|
82
|
-
this.choice = choice ?? (path ? { path: resolve(launchDirectory, path), source: '--config' } : undefined);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
selectedChoice() { return this.choice; }
|
|
86
|
-
|
|
87
|
-
async refresh() {
|
|
88
|
-
this.diagnostics = undefined;
|
|
89
|
-
this.preference = undefined;
|
|
90
|
-
this.preferenceError = undefined;
|
|
91
|
-
this.configuration = undefined;
|
|
92
|
-
this.error = undefined;
|
|
93
|
-
try { this.preference = await readPreference(this.preferencePath); }
|
|
94
|
-
catch { this.preferenceError = 'Cannot use launcher preferences. Select a trusted configuration or forget the preference.'; }
|
|
95
|
-
const remembered = this.preference?.harness === this.harness ? this.preference : undefined;
|
|
96
|
-
this.path = this.choice ? this.choice.path : remembered?.configPath;
|
|
97
|
-
this.source = this.choice?.source ?? (remembered ? 'remembered' : this.isBuiltin ? 'environment' : 'Harness defaults');
|
|
98
|
-
if (!this.choice && this.preferenceError) {
|
|
99
|
-
this.error = this.preferenceError;
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
try {
|
|
103
|
-
if (this.path && !['.ts', '.mts', '.cts', '.mjs', '.js'].includes(extname(this.path))) {
|
|
104
|
-
this.error = 'Choose an explicit trusted TypeScript or ESM module.';
|
|
105
|
-
return;
|
|
106
|
-
}
|
|
107
|
-
const value = this.path ? await loadAnySwarmConfig(this.path)
|
|
108
|
-
: builtin(this.specifier) ? await builtinConfiguration(this.specifier) : undefined;
|
|
109
|
-
if (value === undefined && !this.path) return;
|
|
110
|
-
if (value === null || Array.isArray(value) || typeof value !== 'object' ||
|
|
111
|
-
['cwd', 'prompt', 'input', 'workload'].some(field => Object.hasOwn(value, field))) {
|
|
112
|
-
this.error = 'The configuration must export an object without cwd, prompt, input or workload fields.';
|
|
113
|
-
return;
|
|
114
|
-
}
|
|
115
|
-
this.configuration = { ...value };
|
|
116
|
-
if (Object.hasOwn(budgets, this.specifier)) this.validateRuntime();
|
|
117
|
-
} catch (error) {
|
|
118
|
-
const requirements = /^Set ([A-Z0-9_]+(?: or [A-Z0-9_]+)*) /.exec(error instanceof Error ? error.message : '');
|
|
119
|
-
this.error = !this.path && requirements ? 'Set ' + requirements[1] : this.path
|
|
120
|
-
? 'Could not load the trusted module. Check its path, exported configuration and adjacent .env.'
|
|
121
|
-
: 'Set the model endpoint and Sandbox connection environment, or select a trusted configuration.';
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
private validateRuntime() {
|
|
126
|
-
const config = this.configuration!;
|
|
127
|
-
if (!config.sandbox || !config.models || typeof config.image !== 'string' || !config.image) {
|
|
128
|
-
this.error = 'This Harness requires sandbox, models and a Worker image. Use /config to select a trusted configuration or run setup.';
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
try { selectExecutorDriver(config.executor as Parameters<typeof selectExecutorDriver>[0]); }
|
|
132
|
-
catch { this.error = 'The selected executor is not configured. Run anys setup --backend pi or --backend codex.'; }
|
|
133
|
-
const invalid = budgets[this.specifier].find(({ key, max }) => {
|
|
134
|
-
const value = config[key];
|
|
135
|
-
return value !== undefined && (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > max);
|
|
136
|
-
});
|
|
137
|
-
if (invalid && !this.error) this.error = invalid.key + ' must be between 1 and ' + invalid.max + ' ms.';
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
select(path: string) {
|
|
141
|
-
this.choice = path.trim() ? { path: resolve(this.launchDirectory, path.trim()), source: 'selected for this launch' } :
|
|
142
|
-
{ source: this.isBuiltin ? 'environment (selected)' : 'Harness defaults (selected)' };
|
|
143
|
-
return this.refresh();
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
async remember() {
|
|
147
|
-
if (!this.path || !this.configuration || this.error) throw new Error('Select a valid trusted configuration first.');
|
|
148
|
-
await mkdir(dirname(this.preferencePath), { recursive: true, mode: 0o700 });
|
|
149
|
-
const preference = { version: 1, harness: this.harness, configPath: this.path } as const;
|
|
150
|
-
const temporary = this.preferencePath + '.' + randomUUID();
|
|
151
|
-
try {
|
|
152
|
-
await writeFile(temporary, JSON.stringify(preference) + '\n', { mode: 0o600, flag: 'wx' });
|
|
153
|
-
await rename(temporary, this.preferencePath);
|
|
154
|
-
this.preference = preference;
|
|
155
|
-
this.preferenceError = undefined;
|
|
156
|
-
} finally { await rm(temporary, { force: true }); }
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
async forget() {
|
|
160
|
-
if (await lstat(this.preferencePath).then(() => true, error => {
|
|
161
|
-
if (error.code !== 'ENOENT') throw error;
|
|
162
|
-
return false;
|
|
163
|
-
})) await rm(this.preferencePath);
|
|
164
|
-
await this.refresh();
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
async diagnose(prepare: boolean, signal: AbortSignal, progress: (message: string) => void, backend?: 'pi' | 'codex') {
|
|
168
|
-
if (this.path && !this.configuration) throw new Error('Fix the selected configuration before using setup or doctor.');
|
|
169
|
-
const command = prepare ? { command: 'setup' as const, configPath: this.path, backend } : { command: 'doctor' as const, smoke: false, configPath: this.path };
|
|
170
|
-
const report = await runLocalCommand(command, signal, progress);
|
|
171
|
-
if (prepare && report.ok && !this.path) await this.refresh();
|
|
172
|
-
this.diagnostics = report;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
@@ -1,295 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
-
import type { HarnessEvent, HarnessQuestion, HarnessRequest, HarnessResult, HarnessSession, HarnessState } from '../src/harness/project-harness.js';
|
|
4
|
-
import { terminalObject } from './anyswarm-tui-config.js';
|
|
5
|
-
|
|
6
|
-
function unresolvedHarnessReceipt(value: unknown): boolean {
|
|
7
|
-
const receipt = terminalObject(value);
|
|
8
|
-
const core = terminalObject(receipt.core ?? receipt.result);
|
|
9
|
-
return receipt.status === 'unknown' || core.status === 'unknown' || receipt.disposition === 'unknown' || core.disposition === 'unknown' || core.cleanup === 'pending' || terminalObject(receipt.harnessEffects).status === 'pending';
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
const messageLimit = 96;
|
|
13
|
-
const activityLimit = 100;
|
|
14
|
-
const contentLimit = 16_384;
|
|
15
|
-
const maxPending = 64;
|
|
16
|
-
const readTimeoutMs = 8_000;
|
|
17
|
-
|
|
18
|
-
type Message = {
|
|
19
|
-
order: number;
|
|
20
|
-
agentId: string;
|
|
21
|
-
id: string;
|
|
22
|
-
role: string;
|
|
23
|
-
blocks: Map<number, string>;
|
|
24
|
-
hidden: boolean;
|
|
25
|
-
complete: boolean;
|
|
26
|
-
truncated: boolean;
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
type Activity = { order: number; agentId: string; event: string; summary?: string };
|
|
30
|
-
type Mutation = {
|
|
31
|
-
payload: unknown;
|
|
32
|
-
request: HarnessRequest;
|
|
33
|
-
send: (request: HarnessRequest) => Promise<unknown>;
|
|
34
|
-
status: 'pending' | 'unknown' | 'confirmed' | 'failed';
|
|
35
|
-
receipt?: unknown;
|
|
36
|
-
};
|
|
37
|
-
|
|
38
|
-
export function formatSessionError(error: unknown) {
|
|
39
|
-
const { code, message } = terminalObject(error);
|
|
40
|
-
const detail = typeof message === 'string' ? message.slice(0, 1024) : 'The request failed.';
|
|
41
|
-
return typeof code === 'string' ? code + ' ' + detail : detail;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function boundedMap<K, V>(map: Map<K, V>, key: K, value: V, max: number) {
|
|
45
|
-
map.set(key, value);
|
|
46
|
-
if (map.size > max) map.delete(map.keys().next().value!);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function messageText(message: Record<string, unknown>) {
|
|
50
|
-
if (typeof message.content === 'string') return message.content.slice(0, contentLimit);
|
|
51
|
-
if (!Array.isArray(message.content)) return '';
|
|
52
|
-
let text = '';
|
|
53
|
-
for (const part of message.content.slice(0, 64)) {
|
|
54
|
-
const { type, text: block, name } = terminalObject(part);
|
|
55
|
-
if (type === 'text' && typeof block === 'string') text += block;
|
|
56
|
-
if (type === 'toolCall' && typeof name === 'string') text += '\nTool ' + name;
|
|
57
|
-
if (text.length >= contentLimit) break;
|
|
58
|
-
}
|
|
59
|
-
return text.slice(0, contentLimit);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export class TerminalSession {
|
|
63
|
-
state?: HarnessState;
|
|
64
|
-
revision = 0;
|
|
65
|
-
result?: HarnessResult;
|
|
66
|
-
readonly questions = new Map<string, HarnessQuestion>();
|
|
67
|
-
readonly messages = new Map<string, Message>();
|
|
68
|
-
readonly activity = new Map<string, Activity>();
|
|
69
|
-
readonly operations = new Map<string, Mutation>();
|
|
70
|
-
readonly observations = new Map<string, { pending: boolean; result?: unknown; error?: string }>();
|
|
71
|
-
subscribing = true;
|
|
72
|
-
observationLost = false;
|
|
73
|
-
workerHistoryLost = false;
|
|
74
|
-
runtimeObservationLost = false;
|
|
75
|
-
truncated = false;
|
|
76
|
-
lastError?: string;
|
|
77
|
-
private unsubscribe?: () => void;
|
|
78
|
-
private resubscribe?: ReturnType<typeof setTimeout>;
|
|
79
|
-
private closed = false;
|
|
80
|
-
private anonymousActivity = 0;
|
|
81
|
-
private reading = 0;
|
|
82
|
-
|
|
83
|
-
constructor(readonly session: HarnessSession, private readonly update: () => void) {
|
|
84
|
-
this.subscribe();
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
close() {
|
|
88
|
-
this.closed = true;
|
|
89
|
-
clearTimeout(this.resubscribe);
|
|
90
|
-
this.unsubscribe?.();
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
private subscribe() {
|
|
94
|
-
this.unsubscribe = this.session.onEvent(event => {
|
|
95
|
-
if (this.closed) return;
|
|
96
|
-
try { this.consume(event); }
|
|
97
|
-
catch (error) { this.subscriptionFailed(error); }
|
|
98
|
-
this.update();
|
|
99
|
-
}, { initialSnapshot: true, onError: error => this.subscriptionFailed(error) });
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
private subscriptionFailed(error: unknown) {
|
|
103
|
-
if (this.closed) return;
|
|
104
|
-
this.subscribing = true;
|
|
105
|
-
this.observationLost = true;
|
|
106
|
-
this.lastError = formatSessionError(error);
|
|
107
|
-
this.update();
|
|
108
|
-
if (this.resubscribe) return;
|
|
109
|
-
this.resubscribe = setTimeout(() => {
|
|
110
|
-
this.resubscribe = undefined;
|
|
111
|
-
this.unsubscribe?.();
|
|
112
|
-
try { this.subscribe(); }
|
|
113
|
-
catch (error) { this.subscriptionFailed(error); }
|
|
114
|
-
}, 250);
|
|
115
|
-
this.resubscribe.unref();
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
consume(event: HarnessEvent) {
|
|
119
|
-
switch (event.type) {
|
|
120
|
-
case 'snapshot':
|
|
121
|
-
case 'state':
|
|
122
|
-
if (this.state?.phase !== event.state.phase) {
|
|
123
|
-
this.revision++;
|
|
124
|
-
this.rememberActivity('', 'Run', { phase: event.state.phase });
|
|
125
|
-
}
|
|
126
|
-
this.state = event.state;
|
|
127
|
-
this.truncated ||= event.state.snapshotTruncated === true;
|
|
128
|
-
if (event.type === 'snapshot') {
|
|
129
|
-
this.subscribing = false;
|
|
130
|
-
this.messages.clear();
|
|
131
|
-
this.questions.clear();
|
|
132
|
-
for (const message of event.state.output) this.restoreMessage(message);
|
|
133
|
-
}
|
|
134
|
-
for (const question of event.state.questions) boundedMap(this.questions, question.questionId, question, 96);
|
|
135
|
-
if (event.state.result) this.result = event.state.result;
|
|
136
|
-
break;
|
|
137
|
-
case 'question':
|
|
138
|
-
boundedMap(this.questions, event.question.questionId, event.question, 96);
|
|
139
|
-
break;
|
|
140
|
-
case 'result':
|
|
141
|
-
this.result = event.result;
|
|
142
|
-
for (const question of event.result.questions ?? []) boundedMap(this.questions, question.questionId, question, 96);
|
|
143
|
-
break;
|
|
144
|
-
case 'event':
|
|
145
|
-
this.revision++;
|
|
146
|
-
this.observe(event.event);
|
|
147
|
-
break;
|
|
148
|
-
case 'operation':
|
|
149
|
-
for (const operation of this.operations.values()) {
|
|
150
|
-
if (operation.request.requestId === event.requestId && operation.status !== 'pending') {
|
|
151
|
-
operation.receipt = event.result;
|
|
152
|
-
operation.status = unresolvedHarnessReceipt(event.result) ? 'unknown' : 'confirmed';
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
break;
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
private restoreMessage(value: unknown) {
|
|
160
|
-
const record = terminalObject(value);
|
|
161
|
-
if (typeof record.messageId !== 'string' || typeof record.agentId !== 'string') return;
|
|
162
|
-
const message = this.message(record.agentId, record.messageId);
|
|
163
|
-
if (record.complete) this.finishMessage(message, record.message);
|
|
164
|
-
else if (Array.isArray(record.blocks)) {
|
|
165
|
-
for (const entry of record.blocks.slice(0, 64)) {
|
|
166
|
-
if (Array.isArray(entry) && Number.isSafeInteger(entry[0]) && typeof entry[1] === 'string') {
|
|
167
|
-
message.blocks.set(entry[0], entry[1].slice(-contentLimit));
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
} else if (typeof record.text === 'string') message.blocks.set(0, record.text.slice(-contentLimit));
|
|
171
|
-
message.truncated ||= record.truncated === true;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
private message(agentId: string, id: string) {
|
|
175
|
-
const key = JSON.stringify([agentId, id]);
|
|
176
|
-
let current = this.messages.get(key);
|
|
177
|
-
if (!current) {
|
|
178
|
-
if (this.messages.size >= messageLimit) this.truncated = true;
|
|
179
|
-
current = { order: this.revision, agentId, id, role: 'assistant', blocks: new Map(), hidden: false, complete: false, truncated: false };
|
|
180
|
-
boundedMap(this.messages, key, current, messageLimit);
|
|
181
|
-
}
|
|
182
|
-
return current;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
private finishMessage(message: Message, raw: unknown) {
|
|
186
|
-
const final = terminalObject(raw);
|
|
187
|
-
message.complete = true;
|
|
188
|
-
message.hidden = final.display === false;
|
|
189
|
-
message.role = typeof final.role === 'string' ? final.role : message.role;
|
|
190
|
-
if (final.truncated === true) {
|
|
191
|
-
message.truncated = true;
|
|
192
|
-
return;
|
|
193
|
-
}
|
|
194
|
-
message.blocks.clear();
|
|
195
|
-
if (!message.hidden) message.blocks.set(0, messageText(final));
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
private observe(raw: unknown) {
|
|
199
|
-
const item = terminalObject(raw);
|
|
200
|
-
const event = item.kind === 'agent' ? terminalObject(item.event) : item;
|
|
201
|
-
const author = event.agentId ?? event.agent ?? event.role;
|
|
202
|
-
const agentId = typeof author === 'string' ? author : '';
|
|
203
|
-
const eventName = String(event.type ?? item.kind ?? 'event');
|
|
204
|
-
if (event.type === 'subscriberGap') this.runtimeObservationLost = true;
|
|
205
|
-
if (event.type === 'error' &&
|
|
206
|
-
/worker event history has a gap/i.test(String(terminalObject(event.error).message))) this.workerHistoryLost = true;
|
|
207
|
-
if (event.type !== 'session') {
|
|
208
|
-
if (!['output', 'workerProbe'].includes(eventName)) this.rememberActivity(agentId, eventName, typeof raw === 'string' ? { text: raw } : event);
|
|
209
|
-
return;
|
|
210
|
-
}
|
|
211
|
-
const session = terminalObject(event.event);
|
|
212
|
-
const name = String(session.type ?? 'event');
|
|
213
|
-
if (typeof session.messageId === 'string') {
|
|
214
|
-
const message = this.message(agentId, session.messageId);
|
|
215
|
-
if (name === 'messageStart') {
|
|
216
|
-
if (typeof session.role === 'string') message.role = session.role;
|
|
217
|
-
message.hidden = session.display === false;
|
|
218
|
-
}
|
|
219
|
-
if (name === 'messageEnd') this.finishMessage(message, session.message);
|
|
220
|
-
if (name === 'textDelta' && !message.complete && typeof session.delta === 'string') {
|
|
221
|
-
const index = Number.isSafeInteger(session.blockIndex) ? Number(session.blockIndex) : 0;
|
|
222
|
-
const text = (message.blocks.get(index) ?? '') + session.delta;
|
|
223
|
-
message.truncated ||= text.length > contentLimit || message.blocks.size >= 64;
|
|
224
|
-
boundedMap(message.blocks, index, text.slice(-contentLimit), 64);
|
|
225
|
-
}
|
|
226
|
-
return;
|
|
227
|
-
}
|
|
228
|
-
this.rememberActivity(agentId, name, session);
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
private rememberActivity(agentId: string, event: string, detail: Record<string, unknown>) {
|
|
232
|
-
const toolKey = typeof detail.toolCallId === 'string' ? JSON.stringify([agentId, detail.toolCallId]) : undefined;
|
|
233
|
-
const text = [detail.summary, detail.message, detail.text, detail.toolName, detail.phase, detail.state, detail.status]
|
|
234
|
-
.find((value): value is string => typeof value === 'string');
|
|
235
|
-
const summary = text?.slice(0, 1024).replace(/\s+/g, ' ').slice(0, 280);
|
|
236
|
-
boundedMap(this.activity, toolKey ?? String(this.anonymousActivity++), {
|
|
237
|
-
order: this.revision, agentId, event: event.slice(0, 128), summary,
|
|
238
|
-
}, activityLimit);
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
async mutate(key: string, payload: unknown, send: (request: HarnessRequest) => Promise<unknown>) {
|
|
242
|
-
const previous = this.operations.get(key);
|
|
243
|
-
if (previous?.status === 'pending') return;
|
|
244
|
-
const retry = previous?.status === 'unknown' && isDeepStrictEqual(previous.payload, payload);
|
|
245
|
-
const preservePrevious = !retry && previous?.status === 'unknown';
|
|
246
|
-
if ((!this.operations.has(key) || preservePrevious) && this.operations.size >= maxPending) {
|
|
247
|
-
const settled = [...this.operations].find(([, item]) => item.status === 'confirmed' || item.status === 'failed');
|
|
248
|
-
if (!settled) throw new Error('Operation limit reached. Resolve an unknown operation before sending more.');
|
|
249
|
-
this.operations.delete(settled[0]);
|
|
250
|
-
}
|
|
251
|
-
if (preservePrevious) this.operations.set(key + ':' + previous.request.requestId, previous);
|
|
252
|
-
const operation: Mutation = retry ? previous : { payload, request: { requestId: randomUUID() }, send, status: 'pending' };
|
|
253
|
-
operation.status = 'pending';
|
|
254
|
-
this.operations.set(key, operation);
|
|
255
|
-
this.update();
|
|
256
|
-
try {
|
|
257
|
-
const receipt = await operation.send(operation.request);
|
|
258
|
-
operation.receipt = receipt;
|
|
259
|
-
operation.status = unresolvedHarnessReceipt(receipt) ? 'unknown' : 'confirmed';
|
|
260
|
-
return receipt;
|
|
261
|
-
} catch (error) {
|
|
262
|
-
const { code } = terminalObject(error);
|
|
263
|
-
operation.status = ['RPC_TIMEOUT', 'RPC_DISCONNECTED', 'OPERATION_UNKNOWN'].includes(String(code)) ? 'unknown' : 'failed';
|
|
264
|
-
operation.receipt = formatSessionError(error);
|
|
265
|
-
throw error;
|
|
266
|
-
} finally { if (!this.closed) this.update(); }
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
retry(key: string) {
|
|
270
|
-
const operation = this.operations.get(key);
|
|
271
|
-
if (operation?.status !== 'unknown') return;
|
|
272
|
-
return this.mutate(key, operation.payload, operation.send);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
async read(key: string, query: () => Promise<unknown>) {
|
|
276
|
-
if (this.observations.get(key)?.pending || this.reading >= 4) return;
|
|
277
|
-
this.reading++;
|
|
278
|
-
boundedMap(this.observations, key, { pending: true }, 20);
|
|
279
|
-
this.update();
|
|
280
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
281
|
-
const running = Promise.resolve().then(query);
|
|
282
|
-
void running.finally(() => { this.reading--; }).catch(() => {});
|
|
283
|
-
try {
|
|
284
|
-
const result = await Promise.race([running, new Promise<never>((_, reject) => {
|
|
285
|
-
timer = setTimeout(() => reject(new Error('Read timed out')), readTimeoutMs);
|
|
286
|
-
})]);
|
|
287
|
-
boundedMap(this.observations, key, { pending: false, result }, 20);
|
|
288
|
-
} catch (error) {
|
|
289
|
-
boundedMap(this.observations, key, { pending: false, error: formatSessionError(error) }, 20);
|
|
290
|
-
} finally {
|
|
291
|
-
clearTimeout(timer);
|
|
292
|
-
if (!this.closed) this.update();
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
}
|