@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,9 @@
|
|
|
1
|
+
// Known credential values are replaced in keys as well as values, including common
|
|
2
|
+
// escaped/URL-encoded spellings. Never persist transport configuration in a workflow.
|
|
3
|
+
export function redactCredentials(value, credentials) {
|
|
4
|
+
const patterns = credentials.filter(Boolean).flatMap(secret => [secret, encodeURIComponent(secret), JSON.stringify(secret).slice(1, -1), JSON.stringify(JSON.stringify(secret).slice(1, -1)).slice(1, -1)]).sort((a, b) => b.length - a.length);
|
|
5
|
+
const text = (value) => patterns.reduce((result, secret) => result.split(secret).join('[REDACTED]'), value);
|
|
6
|
+
const visit = (item) => typeof item === 'string' ? text(item) : Array.isArray(item) ? item.map(visit) : item && typeof item === 'object' ? Object.fromEntries(Object.entries(item).map(([key, value]) => [text(key), visit(value)])) : item;
|
|
7
|
+
return visit(value);
|
|
8
|
+
}
|
|
9
|
+
export const credentialKey = /(?:authorization|cookie|password|passphrase|credential|secret|api[-_]?key|access[-_]?token|refresh[-_]?token|bearer|auth[-_]?token)/i;
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { existsSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, join } from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
/**
|
|
6
|
+
* The one place Flow runs git.
|
|
7
|
+
*
|
|
8
|
+
* Every invocation goes through `run`, so the environment, the timeout and the shape of a failure
|
|
9
|
+
* are decided once. Nothing here throws: git is a foreign program, and whether it agreed is data
|
|
10
|
+
* rather than an exception — the same manner `src/daemon/projects.ts` keeps, and load-bearing at
|
|
11
|
+
* the reap site, which must not be able to blow up a timer.
|
|
12
|
+
*
|
|
13
|
+
* **Asked asynchronously, deliberately.** `projects.ts` earns its synchronous `fs` on an explicit
|
|
14
|
+
* bound — a visit budget — and says so: without it, "async would be the only honest choice". No
|
|
15
|
+
* such bound is available here. `git switch` and `git worktree add` run the reader's own
|
|
16
|
+
* `post-checkout` hooks (LFS smudge filters, `npm ci`, code generation) and `worktree add` writes a
|
|
17
|
+
* whole working tree besides. Blocking the loop would stall every SSE subscription, every Shell
|
|
18
|
+
* frame and every other Agent Session's events at once, and the request path already awaits a slow
|
|
19
|
+
* facility inside a GET (`server.ts`'s `shells.available()`), so there is nothing to preserve by
|
|
20
|
+
* going sync. `isRepository` is the one exception, and the reason is below.
|
|
21
|
+
*
|
|
22
|
+
* git runs as the reader's own shell would run it, minus the prompt. No `--no-verify`, no
|
|
23
|
+
* `GIT_CONFIG_NOSYSTEM`: a reader whose hook installs dependencies wants it to run, and a switch
|
|
24
|
+
* that behaves differently under Flow than under their shell is the bug this would be blamed
|
|
25
|
+
* for.
|
|
26
|
+
*/
|
|
27
|
+
/** Reads — `rev-parse`, `status`, `for-each-ref`. Bounded by the size of the repository. */
|
|
28
|
+
export const GIT_READ_TIMEOUT_MS = 10_000;
|
|
29
|
+
/**
|
|
30
|
+
* Writes — `switch`, `worktree add`, `worktree remove`.
|
|
31
|
+
*
|
|
32
|
+
* Generous because the cost is not ours to bound: a `post-checkout` hook may install dependencies,
|
|
33
|
+
* and killing one halfway leaves a working tree in a state nobody asked for. A timeout is here to
|
|
34
|
+
* stop a credential prompt hanging forever, not to discipline someone's hooks.
|
|
35
|
+
*/
|
|
36
|
+
export const GIT_WRITE_TIMEOUT_MS = 120_000;
|
|
37
|
+
/** How many branches `/api/branches` will report before saying it stopped. */
|
|
38
|
+
export const MAX_BRANCHES = 500;
|
|
39
|
+
/** How many names a derived branch or directory will try before giving up. */
|
|
40
|
+
const MAX_CANDIDATES = 50;
|
|
41
|
+
const NAMESPACE = "flow/";
|
|
42
|
+
const exec = promisify(execFile);
|
|
43
|
+
function refuse(attempted, message, code) {
|
|
44
|
+
return { ok: false, failure: { attempted, message, ...(code === undefined ? {} : { code }) } };
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* One git invocation.
|
|
48
|
+
*
|
|
49
|
+
* `-C <dir>` rather than `cwd:`, so a directory that is not there fails as a git error we can
|
|
50
|
+
* report rather than as an ENOENT on spawn, which reads to the caller as a broken daemon.
|
|
51
|
+
*
|
|
52
|
+
* `GIT_TERMINAL_PROMPT=0` because a git that asks for a credential on a daemon with no terminal
|
|
53
|
+
* waits forever, and a refused invocation is strictly better than a hung one. `GIT_OPTIONAL_LOCKS=0`
|
|
54
|
+
* so a read never takes `index.lock` out from under the reader's own terminal.
|
|
55
|
+
*/
|
|
56
|
+
export async function run(directory, args, timeout) {
|
|
57
|
+
const attempted = args.join(" ");
|
|
58
|
+
try {
|
|
59
|
+
const { stdout } = await exec("git", directory === undefined ? args : ["-C", directory, ...args], {
|
|
60
|
+
timeout,
|
|
61
|
+
maxBuffer: 1 << 20,
|
|
62
|
+
encoding: "utf8",
|
|
63
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" },
|
|
64
|
+
});
|
|
65
|
+
return { ok: true, value: stdout };
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
const failed = error;
|
|
69
|
+
const said = (failed.stderr ?? "").trim() || (failed.message ?? "git failed").trim();
|
|
70
|
+
return refuse(attempted, said, typeof failed.code === "number" ? failed.code : undefined);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Whether a directory is a repository.
|
|
75
|
+
*
|
|
76
|
+
* `.git` is tested as a path that *exists*, not as a directory: in a linked worktree or a submodule
|
|
77
|
+
* it is a file containing a `gitdir:` pointer, and treating those as non-repositories would descend
|
|
78
|
+
* into them and offer their subdirectories as Projects.
|
|
79
|
+
*
|
|
80
|
+
* Lives here rather than in `projects.ts` because it is now asked two questions and gives the same
|
|
81
|
+
* answer to both — "should discovery stop here" and "can git be asked about this Scope" — and every
|
|
82
|
+
* worktree this module creates is precisely the `.git`-as-a-file case. One rule, one home.
|
|
83
|
+
*
|
|
84
|
+
* Synchronous, and the one exception to this module's async rule: it is a single `statSync`, and it
|
|
85
|
+
* is the gate that stops any of the functions below spawning a process on a Scope that is not a
|
|
86
|
+
* repository at all.
|
|
87
|
+
*/
|
|
88
|
+
export function isRepository(directory) {
|
|
89
|
+
return statSync(join(directory, ".git"), { throwIfNoEntry: false }) !== undefined;
|
|
90
|
+
}
|
|
91
|
+
let availability;
|
|
92
|
+
/**
|
|
93
|
+
* Whether this machine has git.
|
|
94
|
+
*
|
|
95
|
+
* git is a documented prerequisite rather than a dependency — nothing in `package.json` brings it,
|
|
96
|
+
* and a single-executable build or a bare container has none. Without this, `isRepository` says
|
|
97
|
+
* yes (the `.git` is right there) and every invocation then fails with ENOENT, which is the
|
|
98
|
+
* "offered and broken" failure `/api/config`'s `shell` flag exists to prevent.
|
|
99
|
+
*
|
|
100
|
+
* Memoised on the *promise* rather than on the result, so two concurrent requests spawn one git —
|
|
101
|
+
* the same reason `ShellRegistry` memoises its import that way.
|
|
102
|
+
*/
|
|
103
|
+
export function gitAvailable() {
|
|
104
|
+
availability ??= run(undefined, ["--version"], GIT_READ_TIMEOUT_MS).then((result) => result.ok);
|
|
105
|
+
return availability;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Where the Scope sits now.
|
|
109
|
+
*
|
|
110
|
+
* `symbolic-ref` rather than `rev-parse --abbrev-ref`, because it answers correctly on an *unborn*
|
|
111
|
+
* branch: a repository freshly `git init`ed has a HEAD pointing at `refs/heads/main` with no commit
|
|
112
|
+
* behind it, and `rev-parse` calls that an ambiguous argument while `symbolic-ref` simply says
|
|
113
|
+
* `main`. Failing there would report a new repository as broken rather than as empty.
|
|
114
|
+
*
|
|
115
|
+
* A detached HEAD makes `symbolic-ref` exit non-zero, which is the signal to name the commit
|
|
116
|
+
* instead — reported with `detached` set, never as a branch called `HEAD`.
|
|
117
|
+
*/
|
|
118
|
+
export async function head(scope) {
|
|
119
|
+
const symbolic = await run(scope, ["symbolic-ref", "--short", "-q", "HEAD"], GIT_READ_TIMEOUT_MS);
|
|
120
|
+
if (symbolic.ok)
|
|
121
|
+
return { ok: true, value: { name: symbolic.value.trim() } };
|
|
122
|
+
const commit = await run(scope, ["rev-parse", "--short", "HEAD"], GIT_READ_TIMEOUT_MS);
|
|
123
|
+
if (!commit.ok)
|
|
124
|
+
return commit;
|
|
125
|
+
return { ok: true, value: { name: commit.value.trim(), detached: true } };
|
|
126
|
+
}
|
|
127
|
+
/** Local branches, most recently committed first — the order someone would want to pick from. */
|
|
128
|
+
export async function localBranches(scope) {
|
|
129
|
+
const listed = await run(scope, ["for-each-ref", "--sort=-committerdate", "--format=%(refname:short)", "refs/heads"], GIT_READ_TIMEOUT_MS);
|
|
130
|
+
if (!listed.ok)
|
|
131
|
+
return listed;
|
|
132
|
+
return { ok: true, value: listed.value.split("\n").filter((line) => line !== "") };
|
|
133
|
+
}
|
|
134
|
+
/** Whether the working tree has nothing uncommitted or untracked in it. */
|
|
135
|
+
export async function isClean(scope) {
|
|
136
|
+
const status = await run(scope, ["status", "--porcelain"], GIT_READ_TIMEOUT_MS);
|
|
137
|
+
if (!status.ok)
|
|
138
|
+
return status;
|
|
139
|
+
return { ok: true, value: status.value.trim() === "" };
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* A branch name that git would read as an option.
|
|
143
|
+
*
|
|
144
|
+
* Refused before invoking rather than passed on, because `git switch` has no `--` to hide a name
|
|
145
|
+
* behind, and the failure it produces otherwise is git complaining about a flag nobody typed.
|
|
146
|
+
*/
|
|
147
|
+
function optionLike(branch) {
|
|
148
|
+
return branch.startsWith("-");
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Move the Scope to another branch.
|
|
152
|
+
*
|
|
153
|
+
* `switch` rather than `checkout`: `checkout` also means "restore these paths", so a branch name
|
|
154
|
+
* that happens to also be a path resolves to the wrong one of the two.
|
|
155
|
+
*/
|
|
156
|
+
export async function switchBranch(scope, branch) {
|
|
157
|
+
if (optionLike(branch))
|
|
158
|
+
return refuse(`switch ${branch}`, `not a branch name: ${branch}`);
|
|
159
|
+
const switched = await run(scope, ["switch", branch], GIT_WRITE_TIMEOUT_MS);
|
|
160
|
+
if (!switched.ok)
|
|
161
|
+
return switched;
|
|
162
|
+
return head(scope);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* A branch name as one path segment.
|
|
166
|
+
*
|
|
167
|
+
* Lossy on purpose, and safe to be: nothing ever reads a branch back out of a path, because
|
|
168
|
+
* `SessionMeta.worktree` records the real name. So the segment only has to be unique and legible,
|
|
169
|
+
* and uniqueness is settled by probing for a free one rather than by an escaping scheme that would
|
|
170
|
+
* make the path unreadable to keep a round trip nobody performs.
|
|
171
|
+
*
|
|
172
|
+
* The leading `flow/` of a derived name is dropped: that namespace exists to say who made
|
|
173
|
+
* the branch when read inside the repository, and inside `<stateRoot>/worktrees` it is already said
|
|
174
|
+
* by where the directory is. Keeping it would put "flow-" in front of every label.
|
|
175
|
+
*/
|
|
176
|
+
export function flattenBranch(branch) {
|
|
177
|
+
const named = branch.startsWith(NAMESPACE) ? branch.slice(NAMESPACE.length) : branch;
|
|
178
|
+
const segment = named
|
|
179
|
+
.replace(/[^A-Za-z0-9._-]+/g, "-")
|
|
180
|
+
.replace(/-{2,}/g, "-")
|
|
181
|
+
.replace(/^[-.]+|[-.]+$/g, "")
|
|
182
|
+
.slice(0, 64);
|
|
183
|
+
return segment === "" ? "branch" : segment;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* The branch a new worktree gets when nobody named one.
|
|
187
|
+
*
|
|
188
|
+
* `flow/<base-leaf>-<ms since UTC midnight>`: the namespace so `git branch` in the reader's own
|
|
189
|
+
* terminal says who made it — a branch ref always survives a reap, so these accumulate and have to
|
|
190
|
+
* be attributable later — the base branch's own leaf so two are distinguishable at a glance, and a
|
|
191
|
+
* millisecond-of-day so two cut minutes apart do not collide.
|
|
192
|
+
*
|
|
193
|
+
* **Exactly two segments, always.** Git refs are files, so `refs/heads/flow/main` cannot
|
|
194
|
+
* exist while `refs/heads/flow/main/2` does. Any scheme with a variable number of segments
|
|
195
|
+
* is a trap that fires on the second worktree of the day, so the counter goes inside the last
|
|
196
|
+
* segment and never adds one.
|
|
197
|
+
*
|
|
198
|
+
* This used to be the date, and swapping it is a deliberate trade rather than a tidy-up. The date
|
|
199
|
+
* read better — it was the fact someone used to decide whether they still cared about a branch — but
|
|
200
|
+
* it collided on every worktree after the first each day, so the common case wore a `-2`, `-3`
|
|
201
|
+
* counter that carried no meaning at all. A millisecond-of-day is unique in practice, which retires
|
|
202
|
+
* the counter for derived names; what it costs is legibility, and it is paid knowingly. `git branch`
|
|
203
|
+
* is not where anyone dates a branch — `git log` is.
|
|
204
|
+
*/
|
|
205
|
+
export function derivedBranchName(options) {
|
|
206
|
+
const leaf = flattenBranch(options.from.split("/").pop() ?? options.from);
|
|
207
|
+
return `${NAMESPACE}${leaf}-${millisecondOfDay(options.now)}`;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* How far into the UTC day `now` is, in milliseconds.
|
|
211
|
+
*
|
|
212
|
+
* UTC rather than local, for the reason every other stamp in this codebase is: it is compared
|
|
213
|
+
* against other machines' output and read out of transcripts written elsewhere, and a local-time
|
|
214
|
+
* value is ambiguous the twice a year it matters. Derived from the UTC calendar parts rather than
|
|
215
|
+
* `% 86_400_000` so a leap second cannot push it past a day's worth.
|
|
216
|
+
*/
|
|
217
|
+
function millisecondOfDay(now) {
|
|
218
|
+
const midnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
|
|
219
|
+
return now.getTime() - midnight;
|
|
220
|
+
}
|
|
221
|
+
async function refExists(repo, branch) {
|
|
222
|
+
const found = await run(repo, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], GIT_READ_TIMEOUT_MS);
|
|
223
|
+
return found.ok;
|
|
224
|
+
}
|
|
225
|
+
/** `base`, then `base-2`, `base-3` — the counter inside the last segment, never a new one. */
|
|
226
|
+
function candidate(base, attempt) {
|
|
227
|
+
return attempt === 1 ? base : `${base}-${attempt}`;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* The branch and directory a new worktree would take.
|
|
231
|
+
*
|
|
232
|
+
* The two are probed **independently**, because they collide for unrelated reasons: the directory
|
|
233
|
+
* sits under the repository's *basename*, so `~/a/api` and `~/b/api` share one, and coupling the
|
|
234
|
+
* probes would bump a branch name because an unrelated repository had a name clash — leaving a
|
|
235
|
+
* branch called `flow/main-2026-09-04-2` for a reason nobody could reconstruct.
|
|
236
|
+
*
|
|
237
|
+
* A name the reader supplied is never bumped. Someone who typed a name and got a different one has
|
|
238
|
+
* been ignored, so an existing ref is a failure carrying git's own conclusion; bumping exists only
|
|
239
|
+
* for the derived name, and only because the TUI never types and would otherwise be stuck on the
|
|
240
|
+
* second worktree of the day.
|
|
241
|
+
*/
|
|
242
|
+
export async function planWorktree(options) {
|
|
243
|
+
const { repo, from, under } = options;
|
|
244
|
+
const attempted = `worktree add (from ${from})`;
|
|
245
|
+
if (options.branch !== undefined && optionLike(options.branch)) {
|
|
246
|
+
return refuse(attempted, `not a branch name: ${options.branch}`);
|
|
247
|
+
}
|
|
248
|
+
if (optionLike(from))
|
|
249
|
+
return refuse(attempted, `not a branch name: ${from}`);
|
|
250
|
+
let branch;
|
|
251
|
+
if (options.branch !== undefined) {
|
|
252
|
+
if (await refExists(repo, options.branch)) {
|
|
253
|
+
return refuse(attempted, `a branch named '${options.branch}' already exists`);
|
|
254
|
+
}
|
|
255
|
+
branch = options.branch;
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
const base = derivedBranchName({ from, now: options.now ?? new Date() });
|
|
259
|
+
for (let attempt = 1; attempt <= MAX_CANDIDATES; attempt += 1) {
|
|
260
|
+
const name = candidate(base, attempt);
|
|
261
|
+
if (!(await refExists(repo, name))) {
|
|
262
|
+
branch = name;
|
|
263
|
+
break;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
if (branch === undefined) {
|
|
267
|
+
return refuse(attempted, `no free branch name after ${MAX_CANDIDATES} attempts from ${base}`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const home = join(under, basename(repo));
|
|
271
|
+
const segment = flattenBranch(branch);
|
|
272
|
+
for (let attempt = 1; attempt <= MAX_CANDIDATES; attempt += 1) {
|
|
273
|
+
const path = join(home, candidate(segment, attempt));
|
|
274
|
+
if (!existsSync(path))
|
|
275
|
+
return { ok: true, value: { branch, path } };
|
|
276
|
+
}
|
|
277
|
+
return refuse(attempted, `no free directory after ${MAX_CANDIDATES} attempts in ${home}`);
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Cut a new branch from `from` into a fresh worktree.
|
|
281
|
+
*
|
|
282
|
+
* `-b` is what makes a base branch that is already checked out elsewhere a non-problem: `from` is
|
|
283
|
+
* never checked out, only cut from. Without it, starting a second Agent Session from `main` while
|
|
284
|
+
* the repository itself sits on `main` would be refused by git.
|
|
285
|
+
*/
|
|
286
|
+
export async function createWorktree(options) {
|
|
287
|
+
const planned = await planWorktree(options);
|
|
288
|
+
if (!planned.ok)
|
|
289
|
+
return planned;
|
|
290
|
+
const { branch, path } = planned.value;
|
|
291
|
+
// The leading `<under>/<repo>` is left to git, which creates it. Pre-creating it here left an
|
|
292
|
+
// empty directory behind whenever `worktree add` then failed — a failed creation must leave
|
|
293
|
+
// nothing, because the caller is about to decide there is no Agent Session either.
|
|
294
|
+
const added = await run(options.repo, ["worktree", "add", "-b", branch, path, options.from], GIT_WRITE_TIMEOUT_MS);
|
|
295
|
+
if (!added.ok)
|
|
296
|
+
return added;
|
|
297
|
+
return { ok: true, value: planned.value };
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Remove a worktree this host created.
|
|
301
|
+
*
|
|
302
|
+
* Deliberately no `--force`: the caller has already established the working tree is clean, and a
|
|
303
|
+
* `--force` here would make that check decorative — the whole point is that uncommitted work is
|
|
304
|
+
* never deleted on a timer. Run from the repository rather than from the worktree, so a directory
|
|
305
|
+
* already gone by other means still gets its administrative entry pruned.
|
|
306
|
+
*/
|
|
307
|
+
export async function removeWorktree(options) {
|
|
308
|
+
const removed = await run(options.repo, ["worktree", "remove", options.path], GIT_WRITE_TIMEOUT_MS);
|
|
309
|
+
if (!removed.ok)
|
|
310
|
+
return removed;
|
|
311
|
+
return { ok: true, value: undefined };
|
|
312
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { readBody, send } from "./http.js";
|
|
2
|
+
export async function hostControlRoute(request, response, path, control, admission) {
|
|
3
|
+
if (path === '/api/host' && request.method === 'GET') {
|
|
4
|
+
const { token: _token, ...status } = control.identity;
|
|
5
|
+
send(response, 200, { ...status, stopping: admission.isStopping() });
|
|
6
|
+
return;
|
|
7
|
+
}
|
|
8
|
+
if (path !== '/api/host/stop' || request.method !== 'POST') {
|
|
9
|
+
send(response, 405, {});
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
try {
|
|
13
|
+
const body = JSON.parse(await readBody(request, 4096));
|
|
14
|
+
if (body.instanceId !== control.identity.instanceId) {
|
|
15
|
+
send(response, 409, { error: 'Session Host instance changed' });
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (!admission.isStopping() && (admission.hasPending() || control.hasActiveWork()) && body.force !== true) {
|
|
19
|
+
send(response, 409, { error: 'Session Host has active work; use --force to interrupt it' });
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
admission.stop();
|
|
23
|
+
send(response, 202, { stopping: true });
|
|
24
|
+
setImmediate(() => { void control.stop().catch(error => console.error(error)); });
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
send(response, 400, { error: String(error) });
|
|
28
|
+
}
|
|
29
|
+
}
|