@nathanstephenson/flow 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/README.md +641 -0
- package/build/workflow-runtime.cjs +213964 -0
- package/dist/backend/claude/async-queue.js +44 -0
- package/dist/backend/claude/auto-compaction.js +10 -0
- package/dist/backend/claude/background-calls.js +116 -0
- package/dist/backend/claude/enquiries.js +162 -0
- package/dist/backend/claude/index.js +1138 -0
- package/dist/backend/claude/mcp.js +55 -0
- package/dist/backend/claude/permissions.js +106 -0
- package/dist/backend/claude/streamed-message.js +120 -0
- package/dist/backend/claude/subagents.js +128 -0
- package/dist/backend/claude/workflow-parent.js +12 -0
- package/dist/backend/claude/workflow-processes.js +95 -0
- package/dist/backend/claude/workflow-subagent.js +234 -0
- package/dist/backend/effort.js +30 -0
- package/dist/backend/fake/index.js +570 -0
- package/dist/backend/mcp.js +190 -0
- package/dist/backend/pi/auto-compaction.js +16 -0
- package/dist/backend/pi/background-calls.js +56 -0
- package/dist/backend/pi/enquiries.js +63 -0
- package/dist/backend/pi/index.js +597 -0
- package/dist/backend/pi/mcp.js +35 -0
- package/dist/backend/pi/subagents.js +23 -0
- package/dist/backend/pi/work.js +104 -0
- package/dist/backend/pi/workflow-parent.js +21 -0
- package/dist/backend/pi/workflow-subagent.js +199 -0
- package/dist/backend/registry.js +34 -0
- package/dist/backend/types.js +1 -0
- package/dist/backend/workflow-tools.js +25 -0
- package/dist/build-id +1 -0
- package/dist/cli/application.js +397 -0
- package/dist/cli/bootstrap.js +535 -0
- package/dist/cli/host-control.js +100 -0
- package/dist/cli/install-guard.js +270 -0
- package/dist/cli/install-process.js +52 -0
- package/dist/cli/main.js +12 -0
- package/dist/cli/update.js +128 -0
- package/dist/client/connection.js +183 -0
- package/dist/client/context-usage.js +66 -0
- package/dist/client/diff.js +36 -0
- package/dist/client/enquiry.js +105 -0
- package/dist/client/markdown.js +192 -0
- package/dist/client/model-choices.js +32 -0
- package/dist/client/permission.js +60 -0
- package/dist/client/project-name.js +19 -0
- package/dist/client/reduce.js +463 -0
- package/dist/client/relative-time.js +30 -0
- package/dist/client/scope-kind.js +28 -0
- package/dist/client/search.js +136 -0
- package/dist/client/session-label.js +9 -0
- package/dist/client/status.js +84 -0
- package/dist/client/tool-chains.js +52 -0
- package/dist/client/tool-summary.js +98 -0
- package/dist/daemon/auth.js +590 -0
- package/dist/daemon/config-store.js +183 -0
- package/dist/daemon/config.js +687 -0
- package/dist/daemon/credential-redaction.js +9 -0
- package/dist/daemon/git.js +312 -0
- package/dist/daemon/host-control-routes.js +29 -0
- package/dist/daemon/host.js +2343 -0
- package/dist/daemon/http.js +19 -0
- package/dist/daemon/log.js +44 -0
- package/dist/daemon/mcp-auth.js +164 -0
- package/dist/daemon/models.js +85 -0
- package/dist/daemon/ownership.js +104 -0
- package/dist/daemon/projects.js +317 -0
- package/dist/daemon/publish.js +289 -0
- package/dist/daemon/pull-request.js +198 -0
- package/dist/daemon/runtime.js +100 -0
- package/dist/daemon/secret-store.js +65 -0
- package/dist/daemon/server.js +827 -0
- package/dist/daemon/shell.js +220 -0
- package/dist/daemon/skills.js +104 -0
- package/dist/daemon/stack-metadata.js +24 -0
- package/dist/daemon/stack.js +743 -0
- package/dist/daemon/store.js +130 -0
- package/dist/daemon/summariser.js +476 -0
- package/dist/daemon/workflow-execution-routes.js +105 -0
- package/dist/daemon/workflow-executions.js +1018 -0
- package/dist/daemon/workflow-mcp.js +20 -0
- package/dist/daemon/workflow-routes.js +102 -0
- package/dist/protocol/attachments.js +59 -0
- package/dist/protocol/commands.js +1 -0
- package/dist/protocol/events.js +20 -0
- package/dist/protocol/fonts.js +26 -0
- package/dist/protocol/git.js +12 -0
- package/dist/protocol/mcp.js +51 -0
- package/dist/protocol/projects.js +21 -0
- package/dist/protocol/publish.js +1 -0
- package/dist/protocol/pull-request.js +1 -0
- package/dist/protocol/secrets.js +4 -0
- package/dist/protocol/settings.js +63 -0
- package/dist/protocol/shells.js +8 -0
- package/dist/protocol/skills.js +16 -0
- package/dist/protocol/stack.js +41 -0
- package/dist/protocol/workflow-executions.js +1 -0
- package/dist/protocol/workflows.js +1 -0
- package/dist/tui/app.js +518 -0
- package/dist/tui/keys.js +54 -0
- package/dist/tui/render.js +366 -0
- package/dist/web/assets.js +10 -0
- package/dist/web/embedded.js +12 -0
- package/dist/web/manifest.js +70 -0
- package/dist/workflows/decisions.js +65 -0
- package/dist/workflows/executors.js +132 -0
- package/dist/workflows/graph.js +276 -0
- package/dist/workflows/json-schema.js +49 -0
- package/dist/workflows/loops.js +102 -0
- package/dist/workflows/mcp.js +18 -0
- package/dist/workflows/records.js +111 -0
- package/dist/workflows/recovery.js +25 -0
- package/dist/workflows/runtime-asset.js +17 -0
- package/dist/workflows/runtime-libs.js +1 -0
- package/dist/workflows/runtime-settings.js +23 -0
- package/dist/workflows/runtime.js +343 -0
- package/dist/workflows/scheduler.js +573 -0
- package/dist/workflows/schema.js +161 -0
- package/dist/workflows/store.js +93 -0
- package/package.json +87 -0
- package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
- package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
- package/web/dist/assets/index-BC0gLS53.js +106 -0
- package/web/dist/assets/index-CCeZYKES.css +2 -0
- package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
- package/web/dist/assets/select-6i3wxovH.js +1 -0
- package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
- package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
- package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
- package/web/dist/assets/switch-ftZleVB8.js +6 -0
- package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
- package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
- package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
- package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
- package/web/dist/index.html +31 -0
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { getHostStatus, launchBackground, requestHostStop, requireRestartable, waitUntil } from "./host-control.js";
|
|
4
|
+
import { readHost, oidcFingerprint } from "../daemon/ownership.js";
|
|
5
|
+
import { startRuntime } from "../daemon/runtime.js";
|
|
6
|
+
import { join, resolve } from "node:path";
|
|
7
|
+
import { ConfigStore } from "../daemon/config-store.js";
|
|
8
|
+
import { embeddedWorkflowRuntime } from "../workflows/runtime-asset.js";
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { getAsset, isSea } from 'node:sea';
|
|
11
|
+
import { EMBEDDED } from "../web/embedded.js";
|
|
12
|
+
import { manifestOf, NoWebBuild } from "../web/manifest.js";
|
|
13
|
+
import { defaultStateRoot } from "../daemon/store.js";
|
|
14
|
+
import { connect } from "../client/connection.js";
|
|
15
|
+
import { answerLines } from "../client/enquiry.js";
|
|
16
|
+
import { authorisationLabel } from "../client/permission.js";
|
|
17
|
+
import { initialState, reduce } from "../client/reduce.js";
|
|
18
|
+
import { runTui } from "../tui/app.js";
|
|
19
|
+
const USAGE = `usage:
|
|
20
|
+
flow --version print the installed version
|
|
21
|
+
flow update [--force] update a private global npm installation
|
|
22
|
+
flow tui [--scope DIR] [--backend claude|pi|fake] interactive terminal client
|
|
23
|
+
flow serve [--port N] [--address HOST] run the Session Host in the foreground
|
|
24
|
+
flow serve start|status|stop|restart [--force] control a background Session Host
|
|
25
|
+
flow list list Agent Sessions
|
|
26
|
+
flow [--session ID] [--scope DIR] [--backend B] [--model M] [--effort L] "<prompt>"
|
|
27
|
+
one prompt, then exit
|
|
28
|
+
|
|
29
|
+
tui without --scope uses the Project Root from config.json, else this directory.
|
|
30
|
+
A one-shot prompt always uses this directory unless --scope names another.`;
|
|
31
|
+
function installedVersion() {
|
|
32
|
+
return JSON.parse(isSea() ? getAsset('package.json', 'utf8') : readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The web client to serve. The binary carries its own, injected in place of src/web/embedded.ts at
|
|
36
|
+
* bundle time; a source run has an empty one and reads the Vite build off disk instead.
|
|
37
|
+
*
|
|
38
|
+
* Missing is fatal rather than a silent API-only host: `npm start` builds first (prestart), so an
|
|
39
|
+
* absent web/dist means something skipped that, and a Session Host answering 404 for every page is a
|
|
40
|
+
* far worse thing to debug than a refusal that names the command to run.
|
|
41
|
+
*/
|
|
42
|
+
function webClient() {
|
|
43
|
+
if (Object.keys(EMBEDDED).length > 0)
|
|
44
|
+
return EMBEDDED;
|
|
45
|
+
try {
|
|
46
|
+
return manifestOf(join(import.meta.dirname, "../../web/dist"));
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (!(error instanceof NoWebBuild))
|
|
50
|
+
throw error;
|
|
51
|
+
throw new Error(`${error.message}; run \`npm run build:web\``);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function main() {
|
|
55
|
+
const { values, positionals } = parseArgs({
|
|
56
|
+
allowPositionals: true,
|
|
57
|
+
options: {
|
|
58
|
+
// No default, deliberately: `?? process.cwd()` at each read site would be indistinguishable
|
|
59
|
+
// from the reader having typed it, and the Project Root has to sit between the two.
|
|
60
|
+
scope: { type: "string" },
|
|
61
|
+
backend: { type: "string" },
|
|
62
|
+
model: { type: "string" },
|
|
63
|
+
effort: { type: "string" },
|
|
64
|
+
session: { type: "string" },
|
|
65
|
+
port: { type: "string" },
|
|
66
|
+
address: { type: "string" },
|
|
67
|
+
help: { type: "boolean", default: false },
|
|
68
|
+
version: { type: "boolean", default: false },
|
|
69
|
+
force: { type: 'boolean', default: false },
|
|
70
|
+
'background-host': { type: 'boolean', default: false },
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
if (values.version) {
|
|
74
|
+
console.log(installedVersion());
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
const command = positionals[0];
|
|
78
|
+
if (command === 'update')
|
|
79
|
+
throw new Error('Use flow update [--force]; self-update requires the npm flow executable, not source or SEA');
|
|
80
|
+
if (values.help) {
|
|
81
|
+
console.log(USAGE);
|
|
82
|
+
return 0;
|
|
83
|
+
}
|
|
84
|
+
if (command === "serve") {
|
|
85
|
+
if (positionals.length > 2)
|
|
86
|
+
throw new Error(`Unexpected serve arguments: ${positionals.slice(2).join(' ')}`);
|
|
87
|
+
if (positionals[1])
|
|
88
|
+
return await controlHost(positionals[1], values);
|
|
89
|
+
const { running, daemon, stop } = await startHost(values.port ? Number(values.port) : undefined, values.address, values['background-host'] ? 'background' : 'foreground');
|
|
90
|
+
console.log(`Session Host listening on ${running.url}`);
|
|
91
|
+
if (values.address && values.address !== LOOPBACK) {
|
|
92
|
+
// ADR 0004 binds loopback because tools are pre-approved: reaching this host means running
|
|
93
|
+
// commands as this user. Off-loopback, the bearer token is the only thing in the way.
|
|
94
|
+
console.log(` WARNING: bound to ${values.address}, not loopback. Anything that can route`);
|
|
95
|
+
console.log(" here can run commands as you if it has the token.");
|
|
96
|
+
}
|
|
97
|
+
if (running.oidc) {
|
|
98
|
+
console.log(` browser sign-in: ${running.oidc.config.publicAppUrl}/oauth/login`);
|
|
99
|
+
console.log(` OIDC callback: ${running.oidc.callbackUrl()}`);
|
|
100
|
+
console.log(` back-channel: ${running.oidc.backchannelLogoutUrl()}`);
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
console.log(` web handoff: ${daemon.url}/auth?token=${daemon.token}`);
|
|
104
|
+
}
|
|
105
|
+
await new Promise((resolve) => running.server.on("close", resolve));
|
|
106
|
+
await stop();
|
|
107
|
+
return 0;
|
|
108
|
+
}
|
|
109
|
+
if (command === "tui") {
|
|
110
|
+
const { connection, stop } = await clientConnection();
|
|
111
|
+
try {
|
|
112
|
+
await runTui({
|
|
113
|
+
connection,
|
|
114
|
+
scope: values.scope ?? configuredScope() ?? process.cwd(),
|
|
115
|
+
...(values.backend === undefined ? {} : { backend: values.backend }),
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
await stop();
|
|
120
|
+
}
|
|
121
|
+
return 0;
|
|
122
|
+
}
|
|
123
|
+
if (command === "list") {
|
|
124
|
+
const { connection, stop } = await clientConnection();
|
|
125
|
+
try {
|
|
126
|
+
for (const summary of await connection.listSessions()) {
|
|
127
|
+
console.log(`${summary.id} ${summary.status.padEnd(8)} ${summary.backend.padEnd(7)} ${summary.title}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
await stop();
|
|
132
|
+
}
|
|
133
|
+
return 0;
|
|
134
|
+
}
|
|
135
|
+
const prompt = positionals.join(" ").trim();
|
|
136
|
+
if (!prompt) {
|
|
137
|
+
console.log(USAGE);
|
|
138
|
+
return 1;
|
|
139
|
+
}
|
|
140
|
+
return await oneShot(prompt, values);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The Project Root, for a client that named no Scope.
|
|
144
|
+
*
|
|
145
|
+
* Read straight off disk rather than asked of the daemon, because the TUI may be talking to one it
|
|
146
|
+
* did not start, and `/api/config`'s `scope` falls back to *that process's* working directory —
|
|
147
|
+
* which is not this reader's. Only the configured root is a safe answer to borrow; the fallback to
|
|
148
|
+
* `process.cwd()` has to happen here, where the cwd is the right one.
|
|
149
|
+
*
|
|
150
|
+
* A one-time read rather than a read-through, and that does not contradict ADR 0009: an Agent
|
|
151
|
+
* Session's Scope is fixed for its whole life, so this value is consumed the moment it is asked for
|
|
152
|
+
* and there is no later one for it to go stale against.
|
|
153
|
+
*/
|
|
154
|
+
function configuredScope() {
|
|
155
|
+
return new ConfigStore().projectRoot();
|
|
156
|
+
}
|
|
157
|
+
/** Build a Session Host with every Backend Adapter registered and prior sessions loaded. */
|
|
158
|
+
const LOOPBACK = "127.0.0.1";
|
|
159
|
+
async function startHost(port, address, mode = 'embedded') {
|
|
160
|
+
const runtime = await startRuntime({
|
|
161
|
+
root: defaultStateRoot(), version: installedVersion(), mode, assets: webClient,
|
|
162
|
+
workflowRuntime: () => isSea() ? embeddedWorkflowRuntime() : fileURLToPath(new URL('../../build/workflow-runtime.cjs', import.meta.url)),
|
|
163
|
+
...(port === undefined ? {} : { port }), ...(address === undefined ? {} : { address }),
|
|
164
|
+
});
|
|
165
|
+
const stop = async () => {
|
|
166
|
+
await runtime.stop();
|
|
167
|
+
process.off('SIGINT', signal);
|
|
168
|
+
process.off('SIGTERM', signal);
|
|
169
|
+
process.off('SIGHUP', signal);
|
|
170
|
+
};
|
|
171
|
+
const signal = () => { void stop().then(() => process.exit(0), error => console.error(error)); };
|
|
172
|
+
process.on('SIGINT', signal);
|
|
173
|
+
process.on('SIGTERM', signal);
|
|
174
|
+
process.on('SIGHUP', signal);
|
|
175
|
+
runtime.running.server.once('close', () => {
|
|
176
|
+
process.off('SIGINT', signal);
|
|
177
|
+
process.off('SIGTERM', signal);
|
|
178
|
+
process.off('SIGHUP', signal);
|
|
179
|
+
});
|
|
180
|
+
return { ...runtime, stop };
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Connect to a running Session Host, or run one in this process if there isn't one.
|
|
184
|
+
*
|
|
185
|
+
* Either way the client only ever speaks the wire protocol, so an embedded host is a deployment
|
|
186
|
+
* detail rather than a second code path.
|
|
187
|
+
*/
|
|
188
|
+
async function clientConnection() {
|
|
189
|
+
const existing = readHost(defaultStateRoot());
|
|
190
|
+
if (existing && (await reachable(existing))) {
|
|
191
|
+
return { connection: connect(existing), stop: async () => undefined };
|
|
192
|
+
}
|
|
193
|
+
const { daemon, stop } = await startHost();
|
|
194
|
+
return { connection: connect(daemon), stop };
|
|
195
|
+
}
|
|
196
|
+
async function oneShot(prompt, values) {
|
|
197
|
+
const effort = effortLevel(values.effort);
|
|
198
|
+
const { daemon, stop } = await startHost();
|
|
199
|
+
const connection = connect(daemon);
|
|
200
|
+
try {
|
|
201
|
+
const sessionId = values.session ??
|
|
202
|
+
(await connection.command({
|
|
203
|
+
type: "create",
|
|
204
|
+
scope: values.scope ?? process.cwd(),
|
|
205
|
+
...(values.backend === undefined ? {} : { backend: values.backend }),
|
|
206
|
+
...(values.model ? { modelId: values.model } : {}),
|
|
207
|
+
...(effort ? { effort } : {}),
|
|
208
|
+
}));
|
|
209
|
+
console.log(values.session ? `resuming ${sessionId}` : `session ${sessionId}\n resume with: --session ${sessionId}`);
|
|
210
|
+
let state = initialState();
|
|
211
|
+
let rendered = 0;
|
|
212
|
+
/** The call already refused, so a snapshot arriving while the decision is in flight is ignored. */
|
|
213
|
+
let refused;
|
|
214
|
+
let done;
|
|
215
|
+
const finished = new Promise((resolve) => {
|
|
216
|
+
done = resolve;
|
|
217
|
+
});
|
|
218
|
+
const unsubscribe = connection.subscribe({
|
|
219
|
+
sessionId,
|
|
220
|
+
since: 0,
|
|
221
|
+
onEntry: (entry) => {
|
|
222
|
+
state = reduce(state, entry);
|
|
223
|
+
rendered = render(state, rendered);
|
|
224
|
+
/*
|
|
225
|
+
* Nobody is here to answer, so the Enquiry is aborted rather than waited on.
|
|
226
|
+
*
|
|
227
|
+
* This runner takes one prompt and exits; it has no input at all. An Enquiry holds the turn
|
|
228
|
+
* until a human answers it, so without this the run simply never returns — and a hang is the
|
|
229
|
+
* worst of the three things that could happen, because it looks like a slow model rather
|
|
230
|
+
* than like a question. Aborting ends the turn, which prints the `aborted` row below and
|
|
231
|
+
* gets the transcript written; the Agent Session is left Dormant like any other, so `--session`
|
|
232
|
+
* can pick it up in the TUI or the web client, where it *can* be answered.
|
|
233
|
+
*/
|
|
234
|
+
if (entry.event.type === "enquiry" && entry.event.state === "asked") {
|
|
235
|
+
console.log(" ? the model asked a question, and this runner has no way to answer it");
|
|
236
|
+
console.log(` ? resume with: --session ${sessionId} (or open it in the TUI)`);
|
|
237
|
+
void connection.command({ type: "abort", sessionId });
|
|
238
|
+
}
|
|
239
|
+
/*
|
|
240
|
+
* Denied rather than aborted, which is the one place this parts company with the Enquiry
|
|
241
|
+
* above — and the reason is the third option an Enquiry does not have.
|
|
242
|
+
*
|
|
243
|
+
* A denial is a *complete* answer to a Permission Prompt: the model is told the tool is not
|
|
244
|
+
* available and carries on, which is exactly what this runner did before prompts existed. So
|
|
245
|
+
* refusing keeps `flow "do X"` finishing its turn, where aborting would kill every headless
|
|
246
|
+
* run that touched an MCP tool. An Enquiry has no such answer — nothing stands in for what a
|
|
247
|
+
* human would have chosen — so there, ending the turn is the only honest move.
|
|
248
|
+
*
|
|
249
|
+
* Printed rather than silent, because a refused tool may be the reason the answer is thin,
|
|
250
|
+
* and the human should know where it can be authorised instead.
|
|
251
|
+
*
|
|
252
|
+
* Driven off `state.authorising` rather than off the event, and that is not a style choice.
|
|
253
|
+
* This subscribes at `since: 0`, so `--session` replays the whole transcript — and every
|
|
254
|
+
* `asked` snapshot in it. The reducer already knows which of them was decided afterwards and
|
|
255
|
+
* which is genuinely still waiting, so asking it is what stops a resumed run refusing a
|
|
256
|
+
* dozen long-settled calls. `refused` then stops it sending twice for the one that is open,
|
|
257
|
+
* since `authorising` stays set until the decision comes back over the stream.
|
|
258
|
+
*/
|
|
259
|
+
if (state.authorising && state.authorising.callId !== refused) {
|
|
260
|
+
const { tool, callId } = state.authorising;
|
|
261
|
+
refused = callId;
|
|
262
|
+
console.log(` ! ${tool} needs authorising, and this runner has no way to ask; refusing it`);
|
|
263
|
+
console.log(` ! authorise it with: --session ${sessionId} (or open it in the TUI)`);
|
|
264
|
+
// Rejection swallowed rather than dropped: `--session` resumes a live Agent Session, and a
|
|
265
|
+
// call decided in another client between the reducer seeing it and this landing comes back
|
|
266
|
+
// as a refusal. There is nothing to do about that — the prompt is settled either way — and
|
|
267
|
+
// an unhandled rejection here would take the process down over somebody else's click.
|
|
268
|
+
void connection
|
|
269
|
+
.command({ type: "answer_permission", sessionId, callId, decision: "deny" })
|
|
270
|
+
.catch(() => undefined);
|
|
271
|
+
}
|
|
272
|
+
if (entry.event.type === "turn_ended")
|
|
273
|
+
done?.();
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
await connection.command({ type: "send", sessionId, text: prompt, when: "now" });
|
|
277
|
+
await finished;
|
|
278
|
+
render(state, rendered, true);
|
|
279
|
+
unsubscribe();
|
|
280
|
+
// Leave the session Dormant rather than ending it: the point of a transcript is coming back.
|
|
281
|
+
return 0;
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
await stop();
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Print entries settled since the last render. The final entry is held back while the turn runs,
|
|
289
|
+
* because assistant text arrives as snapshots that keep growing; `flush` releases it at turn end.
|
|
290
|
+
*/
|
|
291
|
+
function render(state, alreadyRendered, flush = false) {
|
|
292
|
+
const settled = flush ? state.entries.length : state.entries.length - 1;
|
|
293
|
+
for (let index = alreadyRendered; index < settled; index += 1) {
|
|
294
|
+
const entry = state.entries[index];
|
|
295
|
+
if (entry)
|
|
296
|
+
console.log(format(entry));
|
|
297
|
+
}
|
|
298
|
+
return Math.max(alreadyRendered, settled);
|
|
299
|
+
}
|
|
300
|
+
function format(entry) {
|
|
301
|
+
switch (entry.kind) {
|
|
302
|
+
case "user":
|
|
303
|
+
return `\n> ${entry.text}`;
|
|
304
|
+
case "assistant":
|
|
305
|
+
return `\n${entry.text}`;
|
|
306
|
+
case "thinking":
|
|
307
|
+
return `\n[thinking] ${entry.text}`;
|
|
308
|
+
case "tool": {
|
|
309
|
+
// The authorisation only when there is one: most rows have none, and printing something for
|
|
310
|
+
// them would suggest a judgement nobody was asked to make.
|
|
311
|
+
const authorised = authorisationLabel(entry.authorisation);
|
|
312
|
+
return ` · ${entry.name} (${entry.status}${authorised ? `, ${authorised}` : ""})`;
|
|
313
|
+
}
|
|
314
|
+
case "subagent":
|
|
315
|
+
return ` ⤷ ${entry.name} (${entry.waitingOn ? `waiting on ${entry.waitingOn}` : entry.status})`;
|
|
316
|
+
case "background_call":
|
|
317
|
+
return ` ⟳ ${entry.tool} in the background (${entry.status})`;
|
|
318
|
+
case "enquiry": {
|
|
319
|
+
// This runner takes no input, so an Enquiry it sees is one it aborts (see `oneShot`) — what
|
|
320
|
+
// reaches here is therefore `aborted`, and what it prints is what was asked and went
|
|
321
|
+
// unanswered. The TUI and the web client are where one can actually be answered.
|
|
322
|
+
const asked = answerLines(entry.questions, entry.answers).join("; ");
|
|
323
|
+
return ` ? [${entry.status}] ${asked}`;
|
|
324
|
+
}
|
|
325
|
+
case "notice":
|
|
326
|
+
return ` ! ${entry.level}: ${entry.text}`;
|
|
327
|
+
case "marker":
|
|
328
|
+
// A break in the Agent Session's life, not a message about it, so it reads as a rule.
|
|
329
|
+
return `\n── ${entry.text} ──`;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
async function startBackground(settings) {
|
|
333
|
+
await launchBackground({
|
|
334
|
+
root: defaultStateRoot(), settings, env: process.env,
|
|
335
|
+
entry: isSea() ? [] : [...process.execArgv, resolve(process.argv[1])],
|
|
336
|
+
});
|
|
337
|
+
console.log('Session Host started');
|
|
338
|
+
}
|
|
339
|
+
async function controlHost(command, values) {
|
|
340
|
+
const identity = readHost(defaultStateRoot());
|
|
341
|
+
const status = identity ? await getHostStatus(identity).catch(() => undefined) : undefined;
|
|
342
|
+
if (command === 'status') {
|
|
343
|
+
console.log(`Installed version: ${installedVersion()}`);
|
|
344
|
+
console.log(status ? `Session Host: ${status.mode} ${status.url}\nRunning version: ${status.version}` : 'Session Host: not reachable');
|
|
345
|
+
return status ? 0 : 1;
|
|
346
|
+
}
|
|
347
|
+
if (command === 'start') {
|
|
348
|
+
if (status)
|
|
349
|
+
throw new Error('A Session Host is already running');
|
|
350
|
+
await startBackground({ port: values.port ? Number(values.port) : 0, address: values.address ?? LOOPBACK, cwd: process.cwd(), oidc: oidcFingerprint() });
|
|
351
|
+
return 0;
|
|
352
|
+
}
|
|
353
|
+
if (command !== 'stop' && command !== 'restart')
|
|
354
|
+
throw new Error(`Unknown serve command: ${command}`);
|
|
355
|
+
if (!identity || !status)
|
|
356
|
+
throw new Error('No reachable Session Host');
|
|
357
|
+
if (command === 'restart')
|
|
358
|
+
requireRestartable(status);
|
|
359
|
+
await requestHostStop(identity, values.force);
|
|
360
|
+
await waitUntil(async () => readHost(defaultStateRoot())?.instanceId !== identity.instanceId, 'Session Host stop timed out; it is still stopping');
|
|
361
|
+
console.log('Session Host stopped');
|
|
362
|
+
if (command === 'restart')
|
|
363
|
+
await startBackground(status.settings);
|
|
364
|
+
return 0;
|
|
365
|
+
}
|
|
366
|
+
/** A bad --effort is worth rejecting outright rather than starting a session that ignores it. */
|
|
367
|
+
function effortLevel(value) {
|
|
368
|
+
if (value === undefined)
|
|
369
|
+
return undefined;
|
|
370
|
+
const levels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
371
|
+
const level = levels.find((candidate) => candidate === value);
|
|
372
|
+
if (!level)
|
|
373
|
+
throw new Error(`--effort must be one of: ${levels.join(", ")}`);
|
|
374
|
+
return level;
|
|
375
|
+
}
|
|
376
|
+
async function reachable(daemon) {
|
|
377
|
+
try {
|
|
378
|
+
const response = await fetch(`${daemon.url}/api/sessions`, {
|
|
379
|
+
headers: { authorization: `Bearer ${daemon.token}` },
|
|
380
|
+
signal: AbortSignal.timeout(500),
|
|
381
|
+
});
|
|
382
|
+
return response.ok;
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
return false;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
export function runCli() {
|
|
389
|
+
return main()
|
|
390
|
+
.then((code) => process.exit(code))
|
|
391
|
+
.catch((error) => {
|
|
392
|
+
console.error(error instanceof Error ? error.message : error);
|
|
393
|
+
if (readHost(defaultStateRoot())?.pid !== process.pid)
|
|
394
|
+
process.exit(1);
|
|
395
|
+
process.exitCode = 1;
|
|
396
|
+
});
|
|
397
|
+
}
|