@sealant/mend 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.
Files changed (4) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +44 -0
  3. package/dist/main.js +466 -0
  4. package/package.json +47 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # mend
2
+
3
+ The CLI for [Mend](https://github.com/sealant-sh/Mend) — a local-first workbench for developers who
4
+ use coding agents heavily. Adopt a repository into Mend's central store, run your agent (Claude
5
+ Code, Codex, or any command) in a recorded per-session git worktree, detach, and reattach from any
6
+ terminal.
7
+
8
+ ```sh
9
+ npm install -g @sealant/mend
10
+ ```
11
+
12
+ Requires Node 22+ and a running Mend server.
13
+
14
+ ## Commands
15
+
16
+ ```
17
+ mend adopt [source] [--name <name>] adopt a repository into the store (default: cwd)
18
+ mend codex|claude|opencode new session worktree + launch the harness in it
19
+ mend run -- <command...> same, with an arbitrary command
20
+ mend attach <session-id-prefix> reattach this terminal to a running session
21
+ mend continue [session-id] resume a session with its pending review follow-up
22
+ mend resume [session-id] [--with h] rejoin a settled session (state restored; --with switches harness)
23
+ mend status active sessions
24
+ ```
25
+
26
+ ## Configuration
27
+
28
+ | Source | What |
29
+ | ------------------ | ------------------------------------------------- |
30
+ | `MEND_URL` | The Mend server (default `http://localhost:3105`) |
31
+ | `MEND_TOKEN` | Bearer token for that server |
32
+ | `~/.mend/cli.json` | `{ "url": ..., "token": ... }` — env vars win |
33
+
34
+ ## How it works
35
+
36
+ Every session runs in its own git worktree over the adopted repository, inside a recorded workspace.
37
+ The terminal you see is a held WebSocket to that workspace's PTY: `Ctrl+]` detaches and the session
38
+ keeps running; `mend attach` reconnects with full scrollback — from this machine or any other that
39
+ can reach the server. When a session settles, Mend harvests the harness's own state into the store,
40
+ so `mend resume` restores it natively (a Claude session resumes with its memory intact, even across
41
+ machines), and `--with` carries the conversation into a different harness.
42
+
43
+ The reviewable object is the session's accumulated local change — worktree versus base — in the Mend
44
+ web app, with the session record beside it. No issue tracker or pull request required.
package/dist/main.js ADDED
@@ -0,0 +1,466 @@
1
+ #!/usr/bin/env node
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ const CONFIG_PATH = path.join(os.homedir(), ".mend", "cli.json");
6
+ const loadConfig = () => {
7
+ let fileConfig = {};
8
+ if (fs.existsSync(CONFIG_PATH)) {
9
+ try {
10
+ fileConfig = JSON.parse(fs.readFileSync(CONFIG_PATH, "utf8"));
11
+ }
12
+ catch {
13
+ fail(`could not parse ${CONFIG_PATH}`);
14
+ }
15
+ }
16
+ return {
17
+ url: process.env["MEND_URL"] ?? fileConfig.url ?? "http://localhost:3105",
18
+ token: process.env["MEND_TOKEN"] ?? fileConfig.token ?? null,
19
+ };
20
+ };
21
+ const fail = (message) => {
22
+ process.stderr.write(`mend: ${message}\n`);
23
+ process.exit(1);
24
+ };
25
+ const paint = (code) => (text) => process.stdout.isTTY ? `[${code}m${text}` : text;
26
+ const dim = paint("2");
27
+ const green = paint("32");
28
+ const amber = paint("33");
29
+ const cobalt = paint("34");
30
+ const say = (line) => process.stdout.write(`${line}\n`);
31
+ const api = async (config, method, route, body) => {
32
+ const headers = { "content-type": "application/json" };
33
+ if (config.token !== null)
34
+ headers["authorization"] = `Bearer ${config.token}`;
35
+ let response;
36
+ try {
37
+ response = await fetch(`${config.url}/api${route}`, {
38
+ method,
39
+ headers,
40
+ // Spread, not `body: null` — fresh oxlint rejects a body key on GETs.
41
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
42
+ });
43
+ }
44
+ catch {
45
+ return fail(`cannot reach the Mend server at ${config.url} — is it running?`);
46
+ }
47
+ if (response.status === 401) {
48
+ return fail(`unauthorized — set MEND_TOKEN (or "token" in ${CONFIG_PATH}) to a bearer token for ${config.url}`);
49
+ }
50
+ const text = await response.text();
51
+ if (!response.ok) {
52
+ try {
53
+ const parsed = JSON.parse(text);
54
+ return fail(parsed.message ?? `${method} ${route} → ${response.status}`);
55
+ }
56
+ catch {
57
+ return fail(`${method} ${route} → ${response.status}`);
58
+ }
59
+ }
60
+ return JSON.parse(text);
61
+ };
62
+ const worktreePathOf = (storePath, worktree) => path.join(path.dirname(storePath), "worktrees", worktree);
63
+ /** A live elapsed-time spinner around a slow await — provisioning is not a hang. */
64
+ const withSpinner = async (label, work) => {
65
+ if (process.stdout.isTTY !== true)
66
+ return work;
67
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
68
+ const started = Date.now();
69
+ let frame = 0;
70
+ const timer = setInterval(() => {
71
+ const seconds = Math.round((Date.now() - started) / 1000);
72
+ process.stdout.write(`\r ${frames[frame % frames.length]} ${label} ${dim(`${seconds}s`)} `);
73
+ frame += 1;
74
+ }, 120);
75
+ try {
76
+ return await work;
77
+ }
78
+ finally {
79
+ clearInterval(timer);
80
+ process.stdout.write("\r");
81
+ }
82
+ };
83
+ // ─── adopt ──────────────────────────────────────────────────────────────────
84
+ const adopt = async (config, args) => {
85
+ const nameFlag = args.indexOf("--name");
86
+ const name = nameFlag !== -1 && args[nameFlag + 1] !== undefined ? String(args[nameFlag + 1]) : null;
87
+ const positional = args.filter((a, i) => !a.startsWith("--") && (nameFlag === -1 || i !== nameFlag + 1));
88
+ const rawSource = positional[0] ?? ".";
89
+ const source = /^(https?|git|ssh):|^git@/.test(rawSource) ? rawSource : path.resolve(rawSource);
90
+ const projectName = name ?? path.basename(source, ".git");
91
+ const project = await api(config, "POST", "/projects", {
92
+ name: projectName,
93
+ source,
94
+ });
95
+ say(`${green("✓")} adopted · ${project.name} · ${dim(project.storePath)}`);
96
+ say(`${dim(" default branch")} ${project.defaultBranch}`);
97
+ say(`${dim(" sessions start with:")} mend codex ${dim("(from anywhere —")} --project ${project.name}${dim(")")}`);
98
+ };
99
+ // ─── session launch ─────────────────────────────────────────────────────────
100
+ const findProject = async (config, explicit) => {
101
+ const projects = await api(config, "GET", "/projects");
102
+ if (explicit !== null) {
103
+ const named = projects.find((p) => p.name === explicit);
104
+ if (named === undefined)
105
+ return fail(`no adopted project named "${explicit}"`);
106
+ return named;
107
+ }
108
+ const cwd = process.cwd();
109
+ const byOrigin = projects.find((p) => p.originUrl !== null && cwd.startsWith(p.originUrl));
110
+ const byName = projects.find((p) => p.name === path.basename(cwd));
111
+ const project = byOrigin ?? byName;
112
+ if (project === undefined) {
113
+ return fail(`no adopted project matches ${cwd} — run "mend adopt" here first, or name one with --project`);
114
+ }
115
+ return project;
116
+ };
117
+ const HARNESS_COMMANDS = {
118
+ codex: ["codex"],
119
+ claude: ["claude"],
120
+ opencode: ["opencode"],
121
+ };
122
+ const launch = async (config, harness, args) => {
123
+ const projectFlag = args.indexOf("--project");
124
+ const explicit = projectFlag !== -1 && args[projectFlag + 1] !== undefined
125
+ ? String(args[projectFlag + 1])
126
+ : null;
127
+ const dashdash = args.indexOf("--");
128
+ const custom = dashdash !== -1 ? args.slice(dashdash + 1) : [];
129
+ const argv = harness === "run" ? custom : (HARNESS_COMMANDS[harness] ?? []);
130
+ if (argv.length === 0) {
131
+ return fail(harness === "run" ? "usage: mend run -- <command...>" : `unknown harness ${harness}`);
132
+ }
133
+ const project = await findProject(config, explicit);
134
+ const session = await api(config, "POST", `/projects/${project.id}/sessions`, {
135
+ harness,
136
+ label: null,
137
+ base: null,
138
+ });
139
+ say(`${green("✓")} worktree ${session.worktree} ${dim(`· branch ${session.branch}`)}`);
140
+ say(`${green("✓")} base ${dim(session.baseSha.slice(0, 12))} · session ${dim(session.id.slice(0, 8))}`);
141
+ say(`${cobalt(" watch")} · ${config.url}/sessions/${session.id}`);
142
+ // Everything runs SUPERVISED (SDK 0.7.0): a workspace mounts the worktree,
143
+ // a platform PTY runs argv, the record begins. Commands tail the record;
144
+ // interactive harnesses get the full terminal bridge.
145
+ if (harness === "run") {
146
+ return supervisedRun(config, session, argv);
147
+ }
148
+ await withSpinner("provisioning workspace — a first launch builds the harness image (can take minutes)…", api(config, "POST", `/sessions/${session.id}/launch`, { argv }));
149
+ say(`${green("✓ recording")} · workspace mounts the worktree · detach: ${dim("Ctrl+]")}`);
150
+ say("");
151
+ await attachTty(config, session.id, 0n);
152
+ const settled = await api(config, "GET", `/sessions/${session.id}`);
153
+ say("");
154
+ say(`${green("✓")} session ${settled.session.status} · recorded`);
155
+ say(`${cobalt(" review")} · ${config.url}/sessions/${session.id}`);
156
+ process.exit(0);
157
+ };
158
+ // ─── the terminal bridge: raw stdin/stdout against the platform PTY ─────────
159
+ /**
160
+ * Attach this terminal to the session's PTY through the Mend server over ONE
161
+ * WebSocket: binary frames are PTY bytes both ways, text frames carry control
162
+ * JSON (resize up, end down). Auth happens once at connect (?token=); after
163
+ * that a keystroke is a frame on an open socket — nothing else on the path.
164
+ * Ctrl+] detaches — the session keeps running and can be reattached from
165
+ * anywhere. Resolves when the session settles or the user detaches.
166
+ */
167
+ const attachTty = async (config, sessionId, from) => {
168
+ const url = new URL(`${config.url}/api/tty`);
169
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
170
+ url.searchParams.set("session", sessionId);
171
+ url.searchParams.set("from", from.toString());
172
+ if (config.token !== null)
173
+ url.searchParams.set("token", config.token);
174
+ const ws = new WebSocket(url);
175
+ ws.binaryType = "arraybuffer";
176
+ try {
177
+ await new Promise((resolve, reject) => {
178
+ ws.addEventListener("open", () => resolve(), { once: true });
179
+ ws.addEventListener("error", () => reject(new Error("could not connect")), { once: true });
180
+ });
181
+ }
182
+ catch {
183
+ return fail(`tty attach unavailable: could not connect to ${url.host}`);
184
+ }
185
+ const sendResize = () => ws.send(JSON.stringify({
186
+ t: "resize",
187
+ cols: process.stdout.columns ?? 80,
188
+ rows: process.stdout.rows ?? 24,
189
+ }));
190
+ sendResize();
191
+ const onWinch = () => sendResize();
192
+ process.stdout.on("resize", onWinch);
193
+ const rawTty = process.stdin.isTTY === true;
194
+ if (rawTty)
195
+ process.stdin.setRawMode(true);
196
+ process.stdin.resume();
197
+ let detached = false;
198
+ const onKeys = (data) => {
199
+ if (data.includes(0x1d)) {
200
+ // Ctrl+] — detach, leave the session running.
201
+ detached = true;
202
+ ws.close();
203
+ return;
204
+ }
205
+ // Copy into a plain ArrayBuffer (WebSocket.send rejects pooled Buffer views).
206
+ ws.send(new Uint8Array(data).buffer);
207
+ };
208
+ process.stdin.on("data", onKeys);
209
+ ws.addEventListener("message", (event) => {
210
+ if (typeof event.data === "string")
211
+ return; // control frames ({"t":"end"}) — close follows
212
+ process.stdout.write(Buffer.from(event.data));
213
+ });
214
+ await new Promise((resolve) => {
215
+ ws.addEventListener("close", () => resolve(), { once: true });
216
+ });
217
+ process.stdin.off("data", onKeys);
218
+ process.stdout.off("resize", onWinch);
219
+ if (rawTty)
220
+ process.stdin.setRawMode(false);
221
+ process.stdin.pause();
222
+ if (detached) {
223
+ say("");
224
+ say(`${amber("detached")} — the session keeps running; reattach: mend attach ${sessionId.slice(0, 8)}`);
225
+ process.exit(0);
226
+ }
227
+ };
228
+ /** Reattach a terminal to a running session (full scrollback replay, then live). */
229
+ const attach = async (config, args) => {
230
+ const prefix = args.find((a) => !a.startsWith("--"));
231
+ if (prefix === undefined)
232
+ return fail("usage: mend attach <session-id-prefix>");
233
+ const sessions = await api(config, "GET", "/sessions");
234
+ const match = sessions.find((s) => s.id.startsWith(prefix));
235
+ if (match === undefined)
236
+ return fail(`no active session matches "${prefix}"`);
237
+ say(`${green("✓")} attaching to ${match.harness} · ${dim(match.id.slice(0, 8))} · detach: ${dim("Ctrl+]")}`);
238
+ say("");
239
+ await attachTty(config, match.id, 0n);
240
+ say("");
241
+ say(`${green("✓")} session settled`);
242
+ process.exit(0);
243
+ };
244
+ // ─── supervised run: platform workspace + PTY + record ──────────────────────
245
+ const supervisedRun = async (config, session, argv) => {
246
+ const launched = await withSpinner("provisioning workspace — a first launch builds the harness image (can take minutes)…", api(config, "POST", `/sessions/${session.id}/launch`, { argv }));
247
+ say(`${green("✓ recording")} · run ${dim(launched.id.slice(0, 8))} · workspace mounts the worktree`);
248
+ say(dim(` ${argv.join(" ")} — live record:`));
249
+ say("");
250
+ // Tail the record through the server's event stream until the session settles.
251
+ const headers = {};
252
+ if (config.token !== null)
253
+ headers["authorization"] = `Bearer ${config.token}`;
254
+ const response = await fetch(`${config.url}/api/events`, { headers });
255
+ if (response.body === null)
256
+ return fail("event stream unavailable");
257
+ const reader = response.body.getReader();
258
+ const decoder = new TextDecoder();
259
+ let buffer = "";
260
+ let settled = null;
261
+ while (settled === null) {
262
+ const { done, value } = await reader.read();
263
+ if (done)
264
+ break;
265
+ buffer += decoder.decode(value, { stream: true });
266
+ const parts = buffer.split("\n\n");
267
+ buffer = parts.pop() ?? "";
268
+ for (const part of parts) {
269
+ const data = part
270
+ .split("\n")
271
+ .filter((line) => line.startsWith("data: "))
272
+ .map((line) => line.slice(6))
273
+ .join("");
274
+ if (data === "")
275
+ continue;
276
+ let event;
277
+ try {
278
+ event = JSON.parse(data);
279
+ }
280
+ catch {
281
+ continue;
282
+ }
283
+ if (event.sessionId !== session.id)
284
+ continue;
285
+ if (event.type === "session-progress" && event.line !== undefined) {
286
+ say(dim(` ${event.line}`));
287
+ }
288
+ if (event.type === "session") {
289
+ const detail = await api(config, "GET", `/sessions/${session.id}`);
290
+ if (["completed", "failed", "stopped"].includes(detail.session.status)) {
291
+ settled = detail.session.status;
292
+ }
293
+ }
294
+ }
295
+ }
296
+ await reader.cancel().catch(() => undefined);
297
+ say("");
298
+ say(`${green("✓")} session ${settled ?? "settled"} · recorded · checkpoint taken`);
299
+ say(`${cobalt(" review")} · ${config.url}/sessions/${session.id}`);
300
+ process.exit(settled === "failed" ? 1 : 0);
301
+ };
302
+ /** How each harness takes an instruction as its opening prompt. */
303
+ const CONTINUE_COMMANDS = {
304
+ codex: (instruction) => ["codex", instruction],
305
+ claude: (instruction) => ["claude", instruction],
306
+ opencode: (instruction) => ["opencode", "run", instruction],
307
+ };
308
+ /**
309
+ * The second half of the review loop (plan §7.3): find the session with a
310
+ * pending follow-up, deliver it (which reopens the session), and relaunch the
311
+ * harness in the same worktree with the instruction as its prompt.
312
+ */
313
+ const continueSession = async (config, args) => {
314
+ const explicitSession = args.find((a) => !a.startsWith("--")) ?? null;
315
+ let sessionId = explicitSession;
316
+ let followUp = null;
317
+ if (sessionId !== null) {
318
+ followUp = await api(config, "GET", `/sessions/${sessionId}/follow-up`);
319
+ if (followUp === null)
320
+ return fail(`session ${sessionId} has no pending follow-up`);
321
+ }
322
+ else {
323
+ // Search the cwd's project, newest sessions first.
324
+ const project = await findProject(config, null);
325
+ const detail = await api(config, "GET", `/projects/${project.id}`);
326
+ for (const candidate of detail.sessions) {
327
+ const pending = await api(config, "GET", `/sessions/${candidate.id}/follow-up`);
328
+ if (pending !== null) {
329
+ sessionId = candidate.id;
330
+ followUp = pending;
331
+ break;
332
+ }
333
+ }
334
+ if (sessionId === null || followUp === null) {
335
+ return fail("no session with a pending follow-up — send one from the review first");
336
+ }
337
+ }
338
+ const detail = await api(config, "GET", `/sessions/${sessionId}`);
339
+ const session = detail.session;
340
+ const projects = await api(config, "GET", "/projects");
341
+ const project = projects.find((p) => p.id === session.projectId);
342
+ if (project === undefined)
343
+ return fail(`project ${session.projectId} not found`);
344
+ const worktree = worktreePathOf(project.storePath, session.worktree);
345
+ const build = CONTINUE_COMMANDS[session.harness];
346
+ say(`${green("✓")} follow-up for session ${dim(session.id.slice(0, 8))} · ${session.branch}`);
347
+ say(dim(" instruction:"));
348
+ for (const line of followUp.instruction.split("\n").slice(0, 6))
349
+ say(dim(` │ ${line}`));
350
+ if (followUp.instruction.split("\n").length > 6)
351
+ say(dim(" │ …"));
352
+ if (build === undefined) {
353
+ say("");
354
+ say(`${amber(" cannot relaunch")} ${dim(`— harness "${session.harness}" has no known resume command.`)}`);
355
+ say(dim(` run it yourself in ${worktree}; the follow-up stays pending.`));
356
+ process.exit(1);
357
+ }
358
+ await api(config, "POST", `/sessions/${session.id}/follow-up/deliver`);
359
+ say(`${green("✓")} delivered · session reopened`);
360
+ say(`${cobalt(" watch")} · ${config.url}/sessions/${session.id}`);
361
+ // Relaunch SUPERVISED, exactly like a fresh `mend <harness>`: a new
362
+ // workspace mounts the SAME worktree, the platform PTY runs the harness
363
+ // with the instruction as its opening prompt, and the record continues —
364
+ // the web session page shows the live terminal throughout.
365
+ const argv = build(followUp.instruction);
366
+ await withSpinner("provisioning workspace — the resumed run records like any other…", api(config, "POST", `/sessions/${session.id}/launch`, { argv }));
367
+ say(`${green("✓ recording")} · workspace mounts the worktree · detach: ${dim("Ctrl+]")}`);
368
+ say("");
369
+ await attachTty(config, session.id, 0n);
370
+ const settled = await api(config, "GET", `/sessions/${session.id}`);
371
+ say("");
372
+ say(`${green("✓")} session ${settled.session.status} · recorded`);
373
+ say(`${cobalt(" review")} · ${config.url}/sessions/${session.id}`);
374
+ process.exit(0);
375
+ };
376
+ // ─── resume: rejoin a session — same worktree, restored harness state ───────
377
+ const ACTIVE_STATUSES = new Set(["starting", "running", "waiting", "idle"]);
378
+ /**
379
+ * Sessions are continuous work, not runs: `mend resume` rejoins one on a
380
+ * fresh workspace — saved harness state restored, a claude resume is native
381
+ * (conversation intact). `--with <harness>` re-opens the same work in a
382
+ * DIFFERENT harness: the conversation crosses as a distilled opening prompt.
383
+ */
384
+ const resumeCommand = async (config, args) => {
385
+ const withFlag = args.indexOf("--with");
386
+ const withHarness = withFlag !== -1 && args[withFlag + 1] !== undefined ? String(args[withFlag + 1]) : null;
387
+ const prefix = args.find((a, i) => !a.startsWith("--") && i !== withFlag + 1);
388
+ const project = await findProject(config, null);
389
+ const detail = await api(config, "GET", `/projects/${project.id}`);
390
+ const match = prefix !== undefined
391
+ ? detail.sessions.find((s) => s.id.startsWith(prefix))
392
+ : detail.sessions.find((s) => !ACTIVE_STATUSES.has(s.status));
393
+ if (match === undefined) {
394
+ return fail(prefix !== undefined
395
+ ? `no session matches "${prefix}"`
396
+ : "no settled session to resume — mend status lists sessions");
397
+ }
398
+ if (ACTIVE_STATUSES.has(match.status)) {
399
+ return fail(`session ${match.id.slice(0, 8)} is live — attach: mend attach ${match.id.slice(0, 8)}`);
400
+ }
401
+ say(`${green("✓")} resuming ${match.harness} · ${dim(match.id.slice(0, 8))}${withHarness === null ? "" : ` ${dim("as")} ${withHarness}`}`);
402
+ say(`${cobalt(" watch")} · ${config.url}/sessions/${match.id}`);
403
+ await withSpinner("resuming — a fresh workspace restores the saved session state…", api(config, "POST", `/sessions/${match.id}/resume`, { harness: withHarness }));
404
+ say(`${green("✓ recording")} · same worktree, conversation restored · detach: ${dim("Ctrl+]")}`);
405
+ say("");
406
+ await attachTty(config, match.id, 0n);
407
+ const settled = await api(config, "GET", `/sessions/${match.id}`);
408
+ say("");
409
+ say(`${green("✓")} session ${settled.session.status} · recorded`);
410
+ say(`${cobalt(" review")} · ${config.url}/sessions/${match.id}`);
411
+ process.exit(0);
412
+ };
413
+ // ─── status ─────────────────────────────────────────────────────────────────
414
+ const status = async (config) => {
415
+ const sessions = await api(config, "GET", "/sessions");
416
+ if (sessions.length === 0) {
417
+ say(dim("no active sessions"));
418
+ return;
419
+ }
420
+ for (const session of sessions) {
421
+ say(`${session.harness} ${dim(session.id.slice(0, 8))} ${session.status} ${dim(session.branch)}`);
422
+ }
423
+ };
424
+ // ─── entry ──────────────────────────────────────────────────────────────────
425
+ const HELP = `mend — the agent workbench
426
+
427
+ mend adopt [source] [--name <name>] adopt a repository into the store (default: cwd)
428
+ mend codex|claude|opencode new session worktree + launch the harness in it
429
+ mend run -- <command...> same, with an arbitrary command
430
+ mend attach <session-id-prefix> reattach this terminal to a running session
431
+ mend continue [session-id] resume a session with its pending review follow-up
432
+ mend resume [session-id] [--with h] rejoin a settled session (state restored; --with switches harness)
433
+ mend status active sessions
434
+
435
+ server: MEND_URL (default http://localhost:3105) · auth: MEND_TOKEN
436
+ config file: ~/.mend/cli.json { "url": ..., "token": ... }
437
+ `;
438
+ const main = async () => {
439
+ const [command, ...rest] = process.argv.slice(2);
440
+ const config = loadConfig();
441
+ switch (command) {
442
+ case "adopt":
443
+ return adopt(config, rest);
444
+ case "codex":
445
+ case "claude":
446
+ case "opencode":
447
+ case "run":
448
+ return launch(config, command, rest);
449
+ case "attach":
450
+ return attach(config, rest);
451
+ case "continue":
452
+ return continueSession(config, rest);
453
+ case "resume":
454
+ return resumeCommand(config, rest);
455
+ case "status":
456
+ return status(config);
457
+ case undefined:
458
+ case "help":
459
+ case "--help":
460
+ say(HELP);
461
+ return;
462
+ default:
463
+ return fail(`unknown command "${command}" — try: mend help`);
464
+ }
465
+ };
466
+ await main();
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@sealant/mend",
3
+ "version": "0.1.0",
4
+ "description": "The mend CLI: adopt a repository into Mend's store, launch your coding agent in a recorded session worktree, detach and reattach from any terminal",
5
+ "keywords": [
6
+ "claude-code",
7
+ "codex",
8
+ "coding-agent",
9
+ "mend",
10
+ "sealant",
11
+ "session",
12
+ "worktree"
13
+ ],
14
+ "homepage": "https://github.com/sealant-sh/Mend",
15
+ "license": "Apache-2.0",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/sealant-sh/Mend.git",
19
+ "directory": "apps/cli"
20
+ },
21
+ "bin": {
22
+ "mend": "./dist/main.js"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "type": "module",
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "devDependencies": {
32
+ "@effect/vitest": "^4.0.0-beta.85",
33
+ "@types/node": "^22.10.2",
34
+ "typescript": "^5.7.2",
35
+ "vitest": "^3.0.5",
36
+ "@mend/typescript": "0.0.0"
37
+ },
38
+ "engines": {
39
+ "node": ">=22"
40
+ },
41
+ "scripts": {
42
+ "build": "tsc src/main.ts --outDir dist --module nodenext --target es2022 --types node --skipLibCheck",
43
+ "lint": "oxlint . --no-error-on-unmatched-pattern",
44
+ "test": "vitest run --passWithNoTests",
45
+ "typecheck": "tsgo -p tsconfig.json --noEmit"
46
+ }
47
+ }