jen-ai 0.0.0-stage → 0.1.0
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/LICENSE +23 -0
- package/README.md +46 -2
- package/cli/api.js +144 -0
- package/cli/browser.js +37 -0
- package/cli/docker.js +172 -0
- package/cli/follow.js +156 -0
- package/cli/jen.js +13 -0
- package/cli/main.js +200 -0
- package/cli/release.js +2 -0
- package/cli/roots.js +61 -0
- package/cli/runtime.js +234 -0
- package/cli/settings.js +128 -0
- package/cli/uninstall.js +104 -0
- package/package.json +14 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
jen license
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 reveer. All rights reserved.
|
|
4
|
+
|
|
5
|
+
reveer grants you a free, worldwide, non-exclusive, non-transferable license
|
|
6
|
+
to install and use jen, for any purpose, including at work and for a business.
|
|
7
|
+
|
|
8
|
+
You may not:
|
|
9
|
+
|
|
10
|
+
- copy, modify, translate or make works based on jen or its code, except for
|
|
11
|
+
the copies made in installing and running it;
|
|
12
|
+
- distribute, sell, rent, sublicense or publish jen or its code, in whole or
|
|
13
|
+
in part;
|
|
14
|
+
- remove or change this notice, or present jen or its code as your own.
|
|
15
|
+
|
|
16
|
+
reveer owns jen, its code and its name. This license gives you no rights to
|
|
17
|
+
them beyond those above. If you break its terms, your license ends.
|
|
18
|
+
|
|
19
|
+
jen is provided "as is", without warranty of any kind. reveer is not liable
|
|
20
|
+
for any damage, loss or cost arising from its use, including charges from
|
|
21
|
+
model providers.
|
|
22
|
+
|
|
23
|
+
reveer may offer later versions of jen under different terms.
|
package/README.md
CHANGED
|
@@ -1,3 +1,47 @@
|
|
|
1
|
-
#
|
|
1
|
+
# jen
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
jen runs AI agents on your machine. Each agent runs in its own container, delegates work to sub-agents of its own kind, and presents itself to you through a UI it builds, which you open in your browser. You talk to your agents from the terminal or that UI.
|
|
4
|
+
|
|
5
|
+
## What you need
|
|
6
|
+
|
|
7
|
+
- **Node 26** or later, from [nodejs.org](https://nodejs.org).
|
|
8
|
+
- **Docker**, with Docker Engine 28.0 or later: [Docker Desktop](https://docs.docker.com/desktop/) on macOS, or [Docker Engine](https://docs.docker.com/engine/install/) on Linux. jen starts Docker Desktop itself when it isn't running.
|
|
9
|
+
- **A key for a model provider that serves OpenAI's Responses API**, such as OpenAI or OpenRouter. Agents use hosted models and run none of their own.
|
|
10
|
+
|
|
11
|
+
jen runs on macOS and Linux.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npm install -g jen-ai
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The command is `jen`. In zsh, a `?` or `*` in a query is a pattern, so add this to `~/.zshrc` to pass them to jen as typed:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
alias jen='noglob jen'
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Use
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
jen new home
|
|
29
|
+
jen @home Remember the word heron.
|
|
30
|
+
jen @home open
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`jen new home` creates an agent named `home`. The first time, jen pulls its images and asks for the model, its base URL, such as `https://api.openai.com/v1` or `https://openrouter.ai/api/v1`, and your key, which `jen config` changes later. `jen @home <query>` sends `home` a query, shows its progress and prints its reply. `jen @home open` opens its UI in your browser.
|
|
34
|
+
|
|
35
|
+
Agents keep running until you stop them, and keep their conversations and files when stopped. `jen stop all` stops every agent. `jen help` lists every command.
|
|
36
|
+
|
|
37
|
+
## Uninstall
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
jen uninstall
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
It deletes every agent, its conversation and files, jen's settings and images, and then the command itself. `npm uninstall -g jen-ai` alone would leave all of that in Docker.
|
|
44
|
+
|
|
45
|
+
## License
|
|
46
|
+
|
|
47
|
+
jen is free to install and use, for any purpose. Its code isn't open source: see [LICENSE](LICENSE).
|
package/cli/api.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// The owner's client of the runtime's API. The runtime's refusals are shown
|
|
2
|
+
// as it words them.
|
|
3
|
+
// The runtime answered with an error status.
|
|
4
|
+
export class ApiError extends Error {
|
|
5
|
+
status;
|
|
6
|
+
constructor(status, message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "ApiError";
|
|
9
|
+
this.status = status;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
// The runtime couldn't be reached at all.
|
|
13
|
+
export class Unanswered extends Error {
|
|
14
|
+
constructor(cause) {
|
|
15
|
+
super(`the runtime didn't answer: ${cause instanceof Error ? (cause.cause instanceof Error ? cause.cause.message : cause.message) : String(cause)}`);
|
|
16
|
+
this.name = "Unanswered";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export class Api {
|
|
20
|
+
base;
|
|
21
|
+
token;
|
|
22
|
+
#fetch;
|
|
23
|
+
constructor(base, token, fetcher = globalThis.fetch) {
|
|
24
|
+
this.base = base;
|
|
25
|
+
this.token = token;
|
|
26
|
+
this.#fetch = fetcher;
|
|
27
|
+
}
|
|
28
|
+
async #call(path, init = {}) {
|
|
29
|
+
let res;
|
|
30
|
+
try {
|
|
31
|
+
res = await this.#fetch(`${this.base}${path}`, { ...init, headers: { authorization: `Bearer ${this.token}`, ...init.headers } });
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (init.signal?.aborted)
|
|
35
|
+
throw error;
|
|
36
|
+
throw new Unanswered(error);
|
|
37
|
+
}
|
|
38
|
+
if (res.ok)
|
|
39
|
+
return res;
|
|
40
|
+
const text = await res.text().catch(() => "");
|
|
41
|
+
let message = text || `${res.status} ${res.statusText}`;
|
|
42
|
+
try {
|
|
43
|
+
message = JSON.parse(text).error ?? message;
|
|
44
|
+
}
|
|
45
|
+
catch { }
|
|
46
|
+
throw new ApiError(res.status, message);
|
|
47
|
+
}
|
|
48
|
+
async #json(path, init = {}) {
|
|
49
|
+
return (await (await this.#call(path, init)).json());
|
|
50
|
+
}
|
|
51
|
+
spawn(name, grant) {
|
|
52
|
+
return this.#json("/agents", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ grant, name }) });
|
|
53
|
+
}
|
|
54
|
+
list() {
|
|
55
|
+
return this.#json("/agents");
|
|
56
|
+
}
|
|
57
|
+
get(id) {
|
|
58
|
+
return this.#json(`/agents/${id}`);
|
|
59
|
+
}
|
|
60
|
+
start(id) {
|
|
61
|
+
return this.#json(`/agents/${id}/start`, { method: "POST" });
|
|
62
|
+
}
|
|
63
|
+
stop(id) {
|
|
64
|
+
return this.#json(`/agents/${id}/stop`, { method: "POST" });
|
|
65
|
+
}
|
|
66
|
+
async post(id, text) {
|
|
67
|
+
const res = await this.#call(`/agents/${id}/messages`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ text }) });
|
|
68
|
+
await res.body?.cancel();
|
|
69
|
+
}
|
|
70
|
+
// The agent's event stream, after lastEventId when given, until it ends or
|
|
71
|
+
// signal fires.
|
|
72
|
+
async events(id, { lastEventId, signal } = {}) {
|
|
73
|
+
const headers = { accept: "text/event-stream" };
|
|
74
|
+
if (lastEventId !== undefined)
|
|
75
|
+
headers["last-event-id"] = String(lastEventId);
|
|
76
|
+
const res = await this.#call(`/agents/${id}/events`, { headers, signal });
|
|
77
|
+
return parseEvents(res.body);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
// Reads Server-Sent Events from body. A stream cut off mid-event drops the
|
|
81
|
+
// partial event, so a reader resuming after the last whole one misses nothing.
|
|
82
|
+
export async function* parseEvents(body) {
|
|
83
|
+
const reader = body.pipeThrough(new TextDecoderStream()).getReader();
|
|
84
|
+
let buffer = "";
|
|
85
|
+
let event = "message";
|
|
86
|
+
let id;
|
|
87
|
+
let data = [];
|
|
88
|
+
try {
|
|
89
|
+
for (;;) {
|
|
90
|
+
let chunk;
|
|
91
|
+
try {
|
|
92
|
+
chunk = await reader.read();
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
// A connection cut off, or closed by the reader, ends the stream.
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (chunk.done)
|
|
99
|
+
return;
|
|
100
|
+
buffer += chunk.value;
|
|
101
|
+
const lines = buffer.split(/\r\n|\n|\r(?!$)/);
|
|
102
|
+
buffer = lines.pop();
|
|
103
|
+
for (const line of lines) {
|
|
104
|
+
if (line === "") {
|
|
105
|
+
if (data.length > 0)
|
|
106
|
+
yield toEvent(event, id, data.join("\n"));
|
|
107
|
+
event = "message";
|
|
108
|
+
id = undefined;
|
|
109
|
+
data = [];
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (line.startsWith(":"))
|
|
113
|
+
continue;
|
|
114
|
+
const colon = line.indexOf(":");
|
|
115
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
116
|
+
let value = colon < 0 ? "" : line.slice(colon + 1);
|
|
117
|
+
if (value.startsWith(" "))
|
|
118
|
+
value = value.slice(1);
|
|
119
|
+
if (field === "event")
|
|
120
|
+
event = value;
|
|
121
|
+
else if (field === "id")
|
|
122
|
+
id = value;
|
|
123
|
+
else if (field === "data")
|
|
124
|
+
data.push(value);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
reader.cancel().catch(() => { });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function toEvent(event, id, data) {
|
|
133
|
+
try {
|
|
134
|
+
const parsed = JSON.parse(data);
|
|
135
|
+
if (event === "item" && id !== undefined)
|
|
136
|
+
return { type: "item", seq: Number(id), item: parsed };
|
|
137
|
+
if (event === "synced" && Number.isSafeInteger(parsed?.seq))
|
|
138
|
+
return { type: "synced", seq: parsed.seq };
|
|
139
|
+
if (event === "error")
|
|
140
|
+
return { type: "error", message: String(parsed?.message ?? data), gaveUp: parsed?.gaveUp === true };
|
|
141
|
+
}
|
|
142
|
+
catch { }
|
|
143
|
+
return { type: "other", event };
|
|
144
|
+
}
|
package/cli/browser.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Opens a URL in the user's browser: with $BROWSER when it's set, `open` on
|
|
2
|
+
// macOS, or `xdg-open` on Linux with a display. Where none applies, such as
|
|
3
|
+
// over SSH, or the opener fails, the URL jen printed is what the user follows.
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
const SETTLE_MS = 3_000;
|
|
6
|
+
export const launch = (program, args) => new Promise((resolve) => {
|
|
7
|
+
const child = spawn(program, args, { detached: true, stdio: "ignore" });
|
|
8
|
+
const timer = setTimeout(() => {
|
|
9
|
+
child.unref();
|
|
10
|
+
resolve(true);
|
|
11
|
+
}, SETTLE_MS);
|
|
12
|
+
child.on("error", () => {
|
|
13
|
+
clearTimeout(timer);
|
|
14
|
+
resolve(false);
|
|
15
|
+
});
|
|
16
|
+
child.on("exit", (code) => {
|
|
17
|
+
clearTimeout(timer);
|
|
18
|
+
resolve(code === 0);
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
// The opener for this system, or undefined when none applies.
|
|
22
|
+
export function opener(env, platform) {
|
|
23
|
+
if (env.BROWSER)
|
|
24
|
+
return env.BROWSER;
|
|
25
|
+
if (platform === "darwin")
|
|
26
|
+
return "open";
|
|
27
|
+
if (platform === "linux" && (env.DISPLAY || env.WAYLAND_DISPLAY))
|
|
28
|
+
return "xdg-open";
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
// Whether the URL was opened.
|
|
32
|
+
export async function openURL(url, { env = process.env, platform = process.platform, run = launch } = {}) {
|
|
33
|
+
const program = opener(env, platform);
|
|
34
|
+
if (program === undefined)
|
|
35
|
+
return false;
|
|
36
|
+
return run(program, [url]);
|
|
37
|
+
}
|
package/cli/docker.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// The engine, reached through the user's own `docker` command, which resolves
|
|
2
|
+
// their context and DOCKER_HOST the way they configured it. Only the calls jen
|
|
3
|
+
// makes are here. A secret reaches a child only through its environment or
|
|
4
|
+
// its stdin, never its arguments, which any user on the machine can read.
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
export const runProcess = (program, args, { env = {}, input } = {}) => new Promise((resolve) => {
|
|
7
|
+
const child = spawn(program, args, { env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "pipe"] });
|
|
8
|
+
let stdout = "";
|
|
9
|
+
let stderr = "";
|
|
10
|
+
child.stdout.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
|
|
11
|
+
child.stderr.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
|
|
12
|
+
child.on("error", (error) => resolve({ code: -1, stdout, stderr: error.message }));
|
|
13
|
+
child.on("close", (code) => resolve({ code: code ?? -1, stdout, stderr }));
|
|
14
|
+
child.stdin.on("error", () => { });
|
|
15
|
+
child.stdin.end(input ?? "");
|
|
16
|
+
});
|
|
17
|
+
// A docker call that failed for a reason jen doesn't expect. Docker's own
|
|
18
|
+
// message is shown as it is.
|
|
19
|
+
export class DockerError extends Error {
|
|
20
|
+
stderr;
|
|
21
|
+
constructor(args, output) {
|
|
22
|
+
super(`docker ${args[0]} failed: ${output.stderr.trim() || `exit code ${output.code}`}`);
|
|
23
|
+
this.name = "DockerError";
|
|
24
|
+
this.stderr = output.stderr;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
// Docker can't run jen: there's no docker command, its engine doesn't answer
|
|
28
|
+
// and jen couldn't start it, or the engine is too old.
|
|
29
|
+
export class EngineError extends Error {
|
|
30
|
+
constructor(message) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.name = "EngineError";
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// The oldest engine jen runs on: agents' network needs an isolated gateway.
|
|
36
|
+
export const MIN_ENGINE = [28, 0];
|
|
37
|
+
// How long a started Docker may take to answer, and how often it's asked.
|
|
38
|
+
export const START_MS = 120_000;
|
|
39
|
+
const START_POLL_MS = 1_000;
|
|
40
|
+
const missing = (stderr) => /no such (container|object|image|volume|network)|not found/i.test(stderr);
|
|
41
|
+
export function createDocker(runner = runProcess, platform = process.platform) {
|
|
42
|
+
const docker = async (args, { env = {}, secrets = {}, guard = [], input } = {}) => {
|
|
43
|
+
for (const value of [...Object.values(secrets), ...guard]) {
|
|
44
|
+
if (value !== "" && args.some((arg) => arg.includes(value)))
|
|
45
|
+
throw new Error("a secret would have been passed as an argument to docker");
|
|
46
|
+
}
|
|
47
|
+
return runner("docker", args, { env: { ...env, ...secrets }, input });
|
|
48
|
+
};
|
|
49
|
+
const ok = async (args) => {
|
|
50
|
+
const output = await docker(args);
|
|
51
|
+
if (output.code !== 0)
|
|
52
|
+
throw new DockerError(args, output);
|
|
53
|
+
return output.stdout;
|
|
54
|
+
};
|
|
55
|
+
const inspectAll = async (ids) => {
|
|
56
|
+
if (ids.length === 0)
|
|
57
|
+
return [];
|
|
58
|
+
const output = await docker(["inspect", "--type", "container", ...ids]);
|
|
59
|
+
// A container removed between the listing and this is left out.
|
|
60
|
+
const found = output.stdout.trim() === "" ? [] : JSON.parse(output.stdout);
|
|
61
|
+
if (output.code !== 0 && found.length === 0 && !missing(output.stderr))
|
|
62
|
+
throw new DockerError(["inspect"], output);
|
|
63
|
+
return found.map((c) => ({
|
|
64
|
+
id: c.Id,
|
|
65
|
+
name: String(c.Name).replace(/^\//, ""),
|
|
66
|
+
image: c.Image,
|
|
67
|
+
state: c.State?.Status ?? "unknown",
|
|
68
|
+
env: c.Config?.Env ?? [],
|
|
69
|
+
labels: c.Config?.Labels ?? {},
|
|
70
|
+
}));
|
|
71
|
+
};
|
|
72
|
+
const removing = async (args) => {
|
|
73
|
+
const output = await docker(args);
|
|
74
|
+
if (output.code !== 0 && !missing(output.stderr))
|
|
75
|
+
throw new DockerError(args, output);
|
|
76
|
+
};
|
|
77
|
+
// How to start the engine by hand, naming a context that isn't Docker's own,
|
|
78
|
+
// since its engine is something else, such as Colima.
|
|
79
|
+
const byHand = async () => {
|
|
80
|
+
const context = (await docker(["context", "show"])).stdout.trim();
|
|
81
|
+
const how = platform === "darwin" ? "Start Docker Desktop and try again." : "Start Docker Desktop, or Docker Engine with: sudo systemctl start docker. Then try again.";
|
|
82
|
+
return context && context !== "default" && context !== "desktop-linux" ? `docker's context is ${context}, so start its engine and try again.` : how;
|
|
83
|
+
};
|
|
84
|
+
return {
|
|
85
|
+
async ensureEngine({ start, say, sleep, now }) {
|
|
86
|
+
const version = () => docker(["version", "--format", "{{.Server.Version}}"]);
|
|
87
|
+
let output = await version();
|
|
88
|
+
if (output.code === -1) {
|
|
89
|
+
if (!start)
|
|
90
|
+
return false;
|
|
91
|
+
throw new EngineError(platform === "darwin"
|
|
92
|
+
? `jen needs Docker, and there's no docker command. Install Docker Desktop: https://docs.docker.com/desktop/setup/install/mac-install/. jen needs Docker Engine ${MIN_ENGINE.join(".")} or later.`
|
|
93
|
+
: `jen needs Docker, and there's no docker command. Install Docker Engine: https://docs.docker.com/engine/install/. jen needs Docker Engine ${MIN_ENGINE.join(".")} or later.`);
|
|
94
|
+
}
|
|
95
|
+
if (output.code !== 0) {
|
|
96
|
+
if (!start)
|
|
97
|
+
return false;
|
|
98
|
+
say("starting docker...");
|
|
99
|
+
let started = (await docker(["desktop", "start", "--detach"])).code === 0;
|
|
100
|
+
// Docker Desktop from before its CLI, or one whose CLI isn't on the path.
|
|
101
|
+
if (!started && platform === "darwin")
|
|
102
|
+
started = (await runner("open", ["-a", "Docker"])).code === 0;
|
|
103
|
+
if (started) {
|
|
104
|
+
const deadline = now() + START_MS;
|
|
105
|
+
for (;;) {
|
|
106
|
+
output = await version();
|
|
107
|
+
if (output.code === 0 || now() >= deadline)
|
|
108
|
+
break;
|
|
109
|
+
await sleep(START_POLL_MS);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (output.code !== 0)
|
|
113
|
+
throw new EngineError(`docker isn't running, and jen couldn't start it${started ? ` within ${START_MS / 1000} seconds` : ""}. ${await byHand()}`);
|
|
114
|
+
}
|
|
115
|
+
const found = output.stdout.trim();
|
|
116
|
+
const [, major, minor] = /^(\d+)\.(\d+)(?:\D|$)/.exec(found) ?? [];
|
|
117
|
+
if (major === undefined || Number(major) < MIN_ENGINE[0] || (Number(major) === MIN_ENGINE[0] && Number(minor) < MIN_ENGINE[1])) {
|
|
118
|
+
throw new EngineError(`jen needs Docker Engine ${MIN_ENGINE.join(".")} or later, and this engine is ${major === undefined ? `${JSON.stringify(found)}, which isn't Docker's` : found}. ` +
|
|
119
|
+
(platform === "darwin" ? "Update Docker Desktop to its latest version." : "Update Docker Engine: https://docs.docker.com/engine/install/."));
|
|
120
|
+
}
|
|
121
|
+
return true;
|
|
122
|
+
},
|
|
123
|
+
async imageId(image) {
|
|
124
|
+
const output = await docker(["image", "inspect", "--format", "{{.Id}}", image]);
|
|
125
|
+
if (output.code === 0)
|
|
126
|
+
return output.stdout.trim();
|
|
127
|
+
if (missing(output.stderr))
|
|
128
|
+
return undefined;
|
|
129
|
+
throw new DockerError(["image", "inspect"], output);
|
|
130
|
+
},
|
|
131
|
+
async inspect(container) {
|
|
132
|
+
return (await inspectAll([container]))[0];
|
|
133
|
+
},
|
|
134
|
+
async containers(labels) {
|
|
135
|
+
const ids = (await ok(["ps", "-aq", "--no-trunc", ...labels.flatMap((l) => ["--filter", `label=${l}`])])).split("\n").filter(Boolean);
|
|
136
|
+
return inspectAll(ids);
|
|
137
|
+
},
|
|
138
|
+
run: (args, options) => docker(["run", ...args], options),
|
|
139
|
+
async port(container) {
|
|
140
|
+
const output = await docker(["port", container, "8080/tcp"]);
|
|
141
|
+
const port = Number(output.stdout.trim().split("\n")[0]?.split(":").at(-1));
|
|
142
|
+
return output.code === 0 && Number.isSafeInteger(port) && port > 0 ? port : undefined;
|
|
143
|
+
},
|
|
144
|
+
async logs(container, lines) {
|
|
145
|
+
const output = await docker(["logs", "--tail", String(lines), container]);
|
|
146
|
+
return (output.stdout + output.stderr).trim();
|
|
147
|
+
},
|
|
148
|
+
remove: (container) => removing(["rm", "-f", container]),
|
|
149
|
+
async volumeExists(name) {
|
|
150
|
+
const output = await docker(["volume", "inspect", name]);
|
|
151
|
+
if (output.code === 0)
|
|
152
|
+
return true;
|
|
153
|
+
if (missing(output.stderr))
|
|
154
|
+
return false;
|
|
155
|
+
throw new DockerError(["volume", "inspect"], output);
|
|
156
|
+
},
|
|
157
|
+
async createVolume(name, labels) {
|
|
158
|
+
await ok(["volume", "create", ...Object.entries(labels).flatMap(([k, v]) => ["--label", v === "" ? k : `${k}=${v}`]), name]);
|
|
159
|
+
},
|
|
160
|
+
async volumes(labels) {
|
|
161
|
+
return (await ok(["volume", "ls", "-q", ...labels.flatMap((l) => ["--filter", `label=${l}`])])).split("\n").filter(Boolean);
|
|
162
|
+
},
|
|
163
|
+
removeVolume: (name) => removing(["volume", "rm", name]),
|
|
164
|
+
removeNetwork: (name) => removing(["network", "rm", name]),
|
|
165
|
+
removeImage: (image) => removing(["image", "rm", image]),
|
|
166
|
+
pull: async (image) => void (await ok(["pull", "--quiet", image])),
|
|
167
|
+
async listImages(pattern) {
|
|
168
|
+
const listed = await ok(["image", "ls", "--filter", `reference=${pattern}`, "--format", "{{.Repository}}:{{.Tag}}"]);
|
|
169
|
+
return [...new Set(listed.split("\n").filter((line) => line !== "" && !line.endsWith(":<none>")))];
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
}
|
package/cli/follow.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// jen @<name> <query>: sends the query to a root and follows its work on the
|
|
2
|
+
// root's event stream until the reply. Everything the stream sends before its
|
|
3
|
+
// first synced is history, and isn't shown. Progress goes to stderr, one line
|
|
4
|
+
// for each tool call, each message from a sub-agent and each error, and the
|
|
5
|
+
// reply to stdout: the text of the first model response after the query's
|
|
6
|
+
// own message with no tool call, read once a synced says every item saved
|
|
7
|
+
// with it has arrived. A root that gives up on its model ends the wait, with
|
|
8
|
+
// its notice.
|
|
9
|
+
import { Api, ApiError, Unanswered } from "./api.js";
|
|
10
|
+
import { READY_MS } from "./runtime.js";
|
|
11
|
+
import { Refusal } from "./settings.js";
|
|
12
|
+
const RETRY_MS = 250;
|
|
13
|
+
// The exit code: 0 with the reply, 1 when the root stopped or gave up first,
|
|
14
|
+
// 130 on Ctrl-C.
|
|
15
|
+
export async function follow(o) {
|
|
16
|
+
const { api, root, query } = o;
|
|
17
|
+
// Whether the query may have reached the root.
|
|
18
|
+
let posted = false;
|
|
19
|
+
const interrupted = () => {
|
|
20
|
+
o.say(posted ? `@${root.name} is still working. To see it, run: jen @${root.name} open` : `nothing was sent to @${root.name}.`);
|
|
21
|
+
return 130;
|
|
22
|
+
};
|
|
23
|
+
if (o.interrupt.aborted)
|
|
24
|
+
return interrupted();
|
|
25
|
+
if (root.state === "stopped")
|
|
26
|
+
await api.start(root.id);
|
|
27
|
+
// Where the stream has been read to, to resume after.
|
|
28
|
+
let last;
|
|
29
|
+
let history = true;
|
|
30
|
+
let found = false;
|
|
31
|
+
// The model response arriving: its text, and whether it called a tool.
|
|
32
|
+
let response = { open: false, text: "", called: false };
|
|
33
|
+
let reply;
|
|
34
|
+
let gaveUp;
|
|
35
|
+
const end = () => {
|
|
36
|
+
if (found && response.open && !response.called && response.text.trim() !== "")
|
|
37
|
+
reply = response.text.trim();
|
|
38
|
+
response = { open: false, text: "", called: false };
|
|
39
|
+
};
|
|
40
|
+
const line = (text) => o.say(cut(text, o.columns));
|
|
41
|
+
const onItem = (item) => {
|
|
42
|
+
if (!found) {
|
|
43
|
+
found = item.type === "message" && item.role === "user" && item.from === "owner" && item.text === query;
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (item.type === "message" && item.role === "assistant") {
|
|
47
|
+
response.open = true;
|
|
48
|
+
response.text += item.text;
|
|
49
|
+
}
|
|
50
|
+
else if (item.type === "tool_call") {
|
|
51
|
+
response.open = true;
|
|
52
|
+
response.called = true;
|
|
53
|
+
line(`→ ${item.name} ${summary(item.input)}`);
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
end();
|
|
57
|
+
if (item.type === "message" && item.role === "user" && item.from !== "owner" && item.from !== "runtime" && item.from !== "")
|
|
58
|
+
line(`← ${item.from}: ${item.text}`);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const onEvent = (event) => {
|
|
62
|
+
if (event.type === "item") {
|
|
63
|
+
last = event.seq;
|
|
64
|
+
if (!history)
|
|
65
|
+
onItem(event.item);
|
|
66
|
+
}
|
|
67
|
+
else if (event.type === "synced") {
|
|
68
|
+
last = event.seq;
|
|
69
|
+
if (!history)
|
|
70
|
+
end();
|
|
71
|
+
}
|
|
72
|
+
else if (event.type === "error" && !history) {
|
|
73
|
+
if (event.gaveUp)
|
|
74
|
+
gaveUp = event.message;
|
|
75
|
+
else
|
|
76
|
+
line(`! ${event.message}`);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
for (;;) {
|
|
80
|
+
const stream = await open(o, last);
|
|
81
|
+
if (stream === "interrupted")
|
|
82
|
+
return interrupted();
|
|
83
|
+
if (stream === "stopped") {
|
|
84
|
+
o.say(`@${root.name} stopped before it replied. Its conversation is kept: send it another query to start it again.`);
|
|
85
|
+
return 1;
|
|
86
|
+
}
|
|
87
|
+
for await (const event of stream) {
|
|
88
|
+
onEvent(event);
|
|
89
|
+
if (event.type === "synced" && history) {
|
|
90
|
+
history = false;
|
|
91
|
+
posted = true;
|
|
92
|
+
await api.post(root.id, query);
|
|
93
|
+
}
|
|
94
|
+
if (reply !== undefined) {
|
|
95
|
+
o.write(`${reply}\n`);
|
|
96
|
+
return 0;
|
|
97
|
+
}
|
|
98
|
+
// Whole, unlike a progress line: it says how to go on.
|
|
99
|
+
if (gaveUp !== undefined) {
|
|
100
|
+
o.say(`! ${gaveUp}`);
|
|
101
|
+
return 1;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (o.interrupt.aborted)
|
|
105
|
+
return interrupted();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// Opens the root's stream after last, waiting for the runtime for as long as
|
|
109
|
+
// a start may take, since it may be being replaced, and for a root that's
|
|
110
|
+
// restarting. A root that's stopped is "stopped".
|
|
111
|
+
async function open(o, last) {
|
|
112
|
+
const deadline = o.now() + READY_MS;
|
|
113
|
+
for (;;) {
|
|
114
|
+
if (o.interrupt.aborted)
|
|
115
|
+
return "interrupted";
|
|
116
|
+
try {
|
|
117
|
+
return await o.api.events(o.root.id, { lastEventId: last, signal: o.interrupt });
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (o.interrupt.aborted)
|
|
121
|
+
return "interrupted";
|
|
122
|
+
if (!(error instanceof Unanswered || (error instanceof ApiError && (error.status === 409 || error.status >= 500))))
|
|
123
|
+
throw error;
|
|
124
|
+
try {
|
|
125
|
+
if ((await o.api.get(o.root.id)).state === "stopped")
|
|
126
|
+
return "stopped";
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
if (!(error instanceof Unanswered || (error instanceof ApiError && error.status >= 500)))
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (o.now() >= deadline)
|
|
134
|
+
throw new Refusal(`the runtime stopped answering while @${o.root.name} worked. Its work goes on; try jen @${o.root.name} open.`);
|
|
135
|
+
await o.sleep(RETRY_MS);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
// A tool call's input in a few words: its values, or its JSON.
|
|
139
|
+
export function summary(input) {
|
|
140
|
+
if (typeof input === "string")
|
|
141
|
+
return input;
|
|
142
|
+
if (typeof input === "object" && input !== null && !Array.isArray(input)) {
|
|
143
|
+
const values = Object.values(input).filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean");
|
|
144
|
+
if (values.length > 0)
|
|
145
|
+
return values.join(" ");
|
|
146
|
+
if (Object.keys(input).length === 0)
|
|
147
|
+
return "";
|
|
148
|
+
}
|
|
149
|
+
return JSON.stringify(input);
|
|
150
|
+
}
|
|
151
|
+
// One line of at most columns characters.
|
|
152
|
+
export function cut(text, columns) {
|
|
153
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
154
|
+
const chars = [...flat];
|
|
155
|
+
return chars.length <= columns ? flat : `${chars.slice(0, Math.max(columns - 1, 1)).join("")}…`;
|
|
156
|
+
}
|
package/cli/jen.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The jen command's entry. It checks Node's version before anything else runs,
|
|
3
|
+
// so it uses nothing newer than Node 18 has and imports the command only once
|
|
4
|
+
// the check passes: an older Node would otherwise stop at syntax or an API it
|
|
5
|
+
// lacks, or, without import.meta.main, exit saying nothing.
|
|
6
|
+
const version = process.versions.node;
|
|
7
|
+
if (Number(version.split(".")[0]) < 26) {
|
|
8
|
+
process.stderr.write(`jen: jen needs Node 26 or later, and this is Node ${version}. Install it from https://nodejs.org.\n`);
|
|
9
|
+
process.exit(1);
|
|
10
|
+
}
|
|
11
|
+
const { start } = await import("./main.js");
|
|
12
|
+
await start();
|
|
13
|
+
export {};
|