appsdoor-laptop 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/dist/Channel.js +69 -0
- package/dist/Home.js +33 -0
- package/dist/Install.js +44 -0
- package/dist/Launchd.js +79 -0
- package/dist/Loop.js +164 -0
- package/dist/Notify.js +15 -0
- package/dist/Secrets.js +38 -0
- package/dist/Setup.js +100 -0
- package/dist/Status.js +48 -0
- package/dist/Version.js +7 -0
- package/dist/command.js +23 -0
- package/dist/harness/Harness.js +8 -0
- package/dist/harness/claude-code.js +136 -0
- package/dist/harness/codex.js +139 -0
- package/dist/harness/fake.js +93 -0
- package/dist/harness/index.js +47 -0
- package/dist/harness/t3-approval.js +196 -0
- package/dist/harness/t3code.js +207 -0
- package/dist/main.js +116 -0
- package/package.json +32 -3
- package/README.md +0 -3
package/dist/Channel.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { Data, Effect } from "effect";
|
|
2
|
+
import { version } from "./Version.js";
|
|
3
|
+
/*
|
|
4
|
+
* The laptop's side of the laptop channel (`docs/seams/laptop-channel.md`):
|
|
5
|
+
* pairing, the long poll for work, and reports, over plain HTTP with the
|
|
6
|
+
* laptop's key. The contract is imported for its types only: plain Node
|
|
7
|
+
* can't load its TypeScript source, so `paths` is checked against it.
|
|
8
|
+
* Each call names the app's version, so Appsdoor can say it is out of date.
|
|
9
|
+
*/
|
|
10
|
+
const paths = {
|
|
11
|
+
pair: "/api/laptops/pair",
|
|
12
|
+
work: "/api/laptops/work",
|
|
13
|
+
report: "/api/laptops/report",
|
|
14
|
+
};
|
|
15
|
+
const versionHeader = "x-appsdoor-laptop-version";
|
|
16
|
+
/** The key was removed or never existed: the laptop must be paired again. */
|
|
17
|
+
export class Unpaired extends Data.TaggedError("Unpaired") {
|
|
18
|
+
}
|
|
19
|
+
/** Appsdoor couldn't be reached, or failed on its side; worth trying again. */
|
|
20
|
+
export class Unreachable extends Data.TaggedError("Unreachable") {
|
|
21
|
+
}
|
|
22
|
+
/** Appsdoor refused the call, saying why. */
|
|
23
|
+
export class Refused extends Data.TaggedError("Refused") {
|
|
24
|
+
}
|
|
25
|
+
const call = (api, path, init = {}) => Effect.tryPromise({
|
|
26
|
+
try: async (signal) => {
|
|
27
|
+
const response = await fetch(new URL(path, api), {
|
|
28
|
+
method: init.body === undefined ? "GET" : "POST",
|
|
29
|
+
headers: {
|
|
30
|
+
[versionHeader]: version,
|
|
31
|
+
...(init.key !== undefined && {
|
|
32
|
+
authorization: `Bearer ${init.key}`,
|
|
33
|
+
}),
|
|
34
|
+
...(init.body !== undefined && {
|
|
35
|
+
"content-type": "application/json",
|
|
36
|
+
}),
|
|
37
|
+
},
|
|
38
|
+
...(init.body !== undefined && { body: JSON.stringify(init.body) }),
|
|
39
|
+
signal,
|
|
40
|
+
});
|
|
41
|
+
const body = await response.json().catch(() => ({}));
|
|
42
|
+
return { status: response.status, body };
|
|
43
|
+
},
|
|
44
|
+
catch: (error) => new Unreachable({
|
|
45
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
46
|
+
}),
|
|
47
|
+
}).pipe(Effect.flatMap(({ status, body }) => {
|
|
48
|
+
if (status < 400)
|
|
49
|
+
return Effect.succeed(body);
|
|
50
|
+
const message = typeof body === "object" &&
|
|
51
|
+
body !== null &&
|
|
52
|
+
"error" in body &&
|
|
53
|
+
typeof body.error === "string"
|
|
54
|
+
? body.error
|
|
55
|
+
: `Appsdoor answered ${status}.`;
|
|
56
|
+
if (status === 401)
|
|
57
|
+
return Effect.fail(new Unpaired());
|
|
58
|
+
if (status >= 500)
|
|
59
|
+
return Effect.fail(new Unreachable({ reason: message }));
|
|
60
|
+
return Effect.fail(new Refused({ status, message }));
|
|
61
|
+
}));
|
|
62
|
+
/** Asks for a pairing code, or, with the secret it came with, whether a member approved it. */
|
|
63
|
+
export const pair = (api, request) => call(api, paths.pair, { body: request }).pipe(Effect.map((body) => body));
|
|
64
|
+
/** The laptop's work; given the last answer's `version`, held until it changes (or 25 s). */
|
|
65
|
+
export const work = (api, key, since) => call(api, since === undefined
|
|
66
|
+
? paths.work
|
|
67
|
+
: `${paths.work}?since=${encodeURIComponent(since)}`, { key }).pipe(Effect.map((body) => body));
|
|
68
|
+
/** Runs one of Laptops' laptop operations as this laptop. */
|
|
69
|
+
export const report = (api, key, body) => call(api, paths.report, { key, body }).pipe(Effect.asVoid);
|
package/dist/Home.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { Effect } from "effect";
|
|
5
|
+
/*
|
|
6
|
+
* The laptop app's state directory: `APPSDOOR_LAPTOP_HOME`, else
|
|
7
|
+
* `~/.appsdoor-laptop`. It holds the config `setup` writes, the status
|
|
8
|
+
* `start` keeps for `status`, and the log. The key lives in the keychain
|
|
9
|
+
* unless `APPSDOOR_LAPTOP_HOME` is set (Secrets.ts).
|
|
10
|
+
*/
|
|
11
|
+
export const homeOverride = process.env.APPSDOOR_LAPTOP_HOME;
|
|
12
|
+
export const home = homeOverride ?? path.join(homedir(), ".appsdoor-laptop");
|
|
13
|
+
export const homeFile = (name) => path.join(home, name);
|
|
14
|
+
export const logFile = homeFile("laptop.log");
|
|
15
|
+
/** The harnesses set up on the laptop. */
|
|
16
|
+
export const harnessesOf = (config) => config.harnesses ?? (config.harness === undefined ? [] : [config.harness]);
|
|
17
|
+
export const readJson = (name) => Effect.promise(async () => {
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(await readFile(homeFile(name), "utf8"));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
/** Writes the file whole, through a rename, so a reader never sees half of it. */
|
|
26
|
+
export const writeJson = (name, value, mode = 0o644) => Effect.promise(async () => {
|
|
27
|
+
await mkdir(home, { recursive: true, mode: 0o700 });
|
|
28
|
+
const temporary = homeFile(`.${name}.${process.pid}`);
|
|
29
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode });
|
|
30
|
+
await rename(temporary, homeFile(name));
|
|
31
|
+
});
|
|
32
|
+
export const readConfig = readJson("config.json");
|
|
33
|
+
export const writeConfig = (config) => writeJson("config.json", config);
|
package/dist/Install.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { Data, Effect } from "effect";
|
|
3
|
+
import { runCommand } from "./command.js";
|
|
4
|
+
import { homeFile } from "./Home.js";
|
|
5
|
+
/*
|
|
6
|
+
* Where the always-on service runs from. A checkout runs its own
|
|
7
|
+
* `src/main.ts`. A published package runs from `node_modules`, and under
|
|
8
|
+
* `npx` that is npm's cache, which npm may clear at any time, so setup
|
|
9
|
+
* installs the same version once more under the state directory
|
|
10
|
+
* (`<home>/app`) and the service runs that copy. Running setup again with
|
|
11
|
+
* a newer version replaces it. `APPSDOOR_LAPTOP_PACKAGE` names what to
|
|
12
|
+
* install instead of `appsdoor-laptop@<version>`, such as a packed
|
|
13
|
+
* tarball tried before it is published.
|
|
14
|
+
*/
|
|
15
|
+
export class InstallFailed extends Data.TaggedError("InstallFailed") {
|
|
16
|
+
}
|
|
17
|
+
const packageName = "appsdoor-laptop";
|
|
18
|
+
/** How long `npm install` may take: the harness SDKs are large. */
|
|
19
|
+
const installTimeoutMs = 5 * 60_000;
|
|
20
|
+
/** Whether `entry` was installed by a package manager rather than run from a checkout. */
|
|
21
|
+
const isPackaged = (entry) => entry.split(path.sep).includes("node_modules");
|
|
22
|
+
/** The file the service runs: `entry` in a checkout, else the copy installed for it under `<home>/app`. */
|
|
23
|
+
export const serviceEntry = (entry, version) => Effect.gen(function* () {
|
|
24
|
+
if (!isPackaged(entry))
|
|
25
|
+
return entry;
|
|
26
|
+
const app = homeFile("app");
|
|
27
|
+
const spec = process.env.APPSDOOR_LAPTOP_PACKAGE ?? `${packageName}@${version}`;
|
|
28
|
+
const ran = yield* runCommand("npm", [
|
|
29
|
+
"install",
|
|
30
|
+
"--prefix",
|
|
31
|
+
app,
|
|
32
|
+
"--omit=dev",
|
|
33
|
+
"--no-audit",
|
|
34
|
+
"--no-fund",
|
|
35
|
+
spec,
|
|
36
|
+
], { timeoutMs: installTimeoutMs });
|
|
37
|
+
if (ran.code !== 0)
|
|
38
|
+
return yield* new InstallFailed({
|
|
39
|
+
message: `npm couldn't install ${spec} for the background service: ${ran.stderr.trim()}`,
|
|
40
|
+
});
|
|
41
|
+
// `entry` sits at the same place inside the installed copy.
|
|
42
|
+
const root = path.dirname(path.dirname(entry));
|
|
43
|
+
return path.join(app, "node_modules", packageName, path.relative(root, entry));
|
|
44
|
+
});
|
package/dist/Launchd.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { Effect } from "effect";
|
|
5
|
+
import { runCommand } from "./command.js";
|
|
6
|
+
import { homeOverride, logFile } from "./Home.js";
|
|
7
|
+
/*
|
|
8
|
+
* The always-on service: a launchd agent, `io.appsdoor.laptop`, that runs
|
|
9
|
+
* `appsdoor-laptop start` at login and again whenever it crashes. It exits
|
|
10
|
+
* cleanly only once the laptop was removed, and then stays stopped. Only
|
|
11
|
+
* this file runs `launchctl` (the Harness seam's named exception).
|
|
12
|
+
*/
|
|
13
|
+
const label = "io.appsdoor.laptop";
|
|
14
|
+
const plistPath = path.join(homedir(), "Library/LaunchAgents", `${label}.plist`);
|
|
15
|
+
const xml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
16
|
+
const plist = (entry) => {
|
|
17
|
+
const environment = {
|
|
18
|
+
PATH: process.env.PATH ?? "/usr/bin:/bin",
|
|
19
|
+
...(homeOverride !== undefined && { APPSDOOR_LAPTOP_HOME: homeOverride }),
|
|
20
|
+
};
|
|
21
|
+
const strings = (values) => values.map((value) => ` <string>${xml(value)}</string>`).join("\n");
|
|
22
|
+
const env = Object.entries(environment)
|
|
23
|
+
.map(([key, value]) => ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`)
|
|
24
|
+
.join("\n");
|
|
25
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
26
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
27
|
+
<plist version="1.0">
|
|
28
|
+
<dict>
|
|
29
|
+
<key>Label</key>
|
|
30
|
+
<string>${label}</string>
|
|
31
|
+
<key>ProgramArguments</key>
|
|
32
|
+
<array>
|
|
33
|
+
${strings([process.execPath, entry, "start"])}
|
|
34
|
+
</array>
|
|
35
|
+
<key>EnvironmentVariables</key>
|
|
36
|
+
<dict>
|
|
37
|
+
${env}
|
|
38
|
+
</dict>
|
|
39
|
+
<key>RunAtLoad</key>
|
|
40
|
+
<true/>
|
|
41
|
+
<key>KeepAlive</key>
|
|
42
|
+
<dict>
|
|
43
|
+
<key>SuccessfulExit</key>
|
|
44
|
+
<false/>
|
|
45
|
+
</dict>
|
|
46
|
+
<key>ThrottleInterval</key>
|
|
47
|
+
<integer>10</integer>
|
|
48
|
+
<key>StandardOutPath</key>
|
|
49
|
+
<string>/dev/null</string>
|
|
50
|
+
<key>StandardErrorPath</key>
|
|
51
|
+
<string>${xml(logFile)}</string>
|
|
52
|
+
</dict>
|
|
53
|
+
</plist>
|
|
54
|
+
`;
|
|
55
|
+
};
|
|
56
|
+
/** Writes the agent's plist and (re)loads it, so `start` runs now and at every login. */
|
|
57
|
+
export const installService = (entry) => Effect.gen(function* () {
|
|
58
|
+
yield* Effect.promise(async () => {
|
|
59
|
+
await mkdir(path.dirname(plistPath), { recursive: true });
|
|
60
|
+
await writeFile(plistPath, plist(entry));
|
|
61
|
+
});
|
|
62
|
+
const domain = `gui/${process.getuid?.() ?? 501}`;
|
|
63
|
+
// Unloading a running agent first lets setup run again over it.
|
|
64
|
+
yield* runCommand("launchctl", ["bootout", `${domain}/${label}`]);
|
|
65
|
+
// bootout returns before the old agent is gone, and loading over it
|
|
66
|
+
// fails ("Bootstrap failed: 5: Input/output error"), so try again.
|
|
67
|
+
let loaded = yield* runCommand("launchctl", [
|
|
68
|
+
"bootstrap",
|
|
69
|
+
domain,
|
|
70
|
+
plistPath,
|
|
71
|
+
]);
|
|
72
|
+
for (let tries = 1; loaded.code !== 0 && tries < 10; tries++) {
|
|
73
|
+
yield* Effect.sleep("1 second");
|
|
74
|
+
loaded = yield* runCommand("launchctl", ["bootstrap", domain, plistPath]);
|
|
75
|
+
}
|
|
76
|
+
if (loaded.code !== 0)
|
|
77
|
+
return yield* Effect.die(new Error(`launchctl couldn't load ${plistPath}: ${loaded.stderr.trim()}`));
|
|
78
|
+
return plistPath;
|
|
79
|
+
});
|
package/dist/Loop.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { Duration, Effect, Fiber, Stream } from "effect";
|
|
4
|
+
import * as Channel from "./Channel.js";
|
|
5
|
+
import { adapters, harnessIdOf } from "./harness/index.js";
|
|
6
|
+
import { log, makeStatus } from "./Status.js";
|
|
7
|
+
/*
|
|
8
|
+
* `appsdoor-laptop start`: holds a long poll on the laptop channel and
|
|
9
|
+
* brings each Pickup's coding thread to what Appsdoor wants, in the
|
|
10
|
+
* Pickup's own harness among the ones set up here, reporting back what
|
|
11
|
+
* the harness did and posting each reply. It backs off while
|
|
12
|
+
* Appsdoor can't be reached and ends, answering `"unpaired"`, once the
|
|
13
|
+
* laptop's key stops working.
|
|
14
|
+
*/
|
|
15
|
+
const removedMessage = "This laptop was removed. Run appsdoor-laptop setup again.";
|
|
16
|
+
const longestBackoff = Duration.seconds(30);
|
|
17
|
+
const expandHome = (folder) => folder.startsWith("~/") ? path.join(homedir(), folder.slice(2)) : folder;
|
|
18
|
+
/** The first message of a new coding thread: the card's title, a blank line, its notes. */
|
|
19
|
+
const promptOf = (pickup) => pickup.notes.trim() === ""
|
|
20
|
+
? pickup.title
|
|
21
|
+
: `${pickup.title}\n\n${pickup.notes}`;
|
|
22
|
+
/** The state a Pickup's coding thread should reach. */
|
|
23
|
+
const targetOf = (pickup) => pickup.wanted === "closed" ? "finished" : pickup.wanted;
|
|
24
|
+
/** Whether the harness has something to do for the Pickup. A failed one waits for a member's Retry. */
|
|
25
|
+
const needsWork = (pickup) => !(pickup.state === "failed" && pickup.wanted === "running") &&
|
|
26
|
+
(pickup.state !== targetOf(pickup) ||
|
|
27
|
+
(pickup.wanted === "running" && pickup.messages.length > 0));
|
|
28
|
+
export const runLoop = (config, key, harnesses) => Effect.gen(function* () {
|
|
29
|
+
const status = makeStatus();
|
|
30
|
+
const report = (input) => Channel.report(config.api, key, { operation: "reportPickup", input });
|
|
31
|
+
const watchers = new Map();
|
|
32
|
+
/** Posts the thread's replies to its Pickup's card for as long as it runs. */
|
|
33
|
+
const watch = (pickup, thread) => Effect.gen(function* () {
|
|
34
|
+
const harness = harnesses.get(pickup.harness);
|
|
35
|
+
if (watchers.has(thread) || harness === undefined)
|
|
36
|
+
return;
|
|
37
|
+
const fiber = yield* harness.replies(thread).pipe(Stream.runForEach((text) => Channel.report(config.api, key, {
|
|
38
|
+
operation: "postReply",
|
|
39
|
+
input: { pickup: pickup.id, text },
|
|
40
|
+
}).pipe(Effect.catch((error) => status.failed(pickup.title, `Its reply wasn't posted: ${messageOf(error)}`)))), Effect.forkDetach);
|
|
41
|
+
watchers.set(thread, fiber);
|
|
42
|
+
});
|
|
43
|
+
const unwatch = (thread) => Effect.gen(function* () {
|
|
44
|
+
const fiber = watchers.get(thread);
|
|
45
|
+
if (fiber === undefined)
|
|
46
|
+
return;
|
|
47
|
+
watchers.delete(thread);
|
|
48
|
+
yield* Fiber.interrupt(fiber);
|
|
49
|
+
});
|
|
50
|
+
const work = (pickup) => Effect.gen(function* () {
|
|
51
|
+
if (!needsWork(pickup))
|
|
52
|
+
return;
|
|
53
|
+
const live = harnesses.get(pickup.harness);
|
|
54
|
+
const health = live === undefined
|
|
55
|
+
? {
|
|
56
|
+
_tag: "Unavailable",
|
|
57
|
+
reason: `${adapters[harnessIdOf(pickup.harness)].name} isn't set up on ${config.name}. Run appsdoor-laptop setup --harness ${harnessIdOf(pickup.harness)} on it, then press Retry.`,
|
|
58
|
+
}
|
|
59
|
+
: yield* live.health;
|
|
60
|
+
const messages = pickup.wanted === "running" ? pickup.messages : [];
|
|
61
|
+
const converged = health._tag === "Unavailable" || live === undefined
|
|
62
|
+
? {
|
|
63
|
+
_tag: "Failed",
|
|
64
|
+
reason: health._tag === "Unavailable" ? health.reason : "No harness.",
|
|
65
|
+
}
|
|
66
|
+
: yield* live
|
|
67
|
+
.converge({
|
|
68
|
+
runId: pickup.runId,
|
|
69
|
+
thread: pickup.codingThread,
|
|
70
|
+
folder: expandHome(pickup.folder),
|
|
71
|
+
prompt: promptOf(pickup),
|
|
72
|
+
want: pickup.wanted,
|
|
73
|
+
messages: messages.map(({ body }) => body),
|
|
74
|
+
})
|
|
75
|
+
.pipe(Effect.map((done) => ({ _tag: "Done", ...done })), Effect.catch((failure) => Effect.succeed({
|
|
76
|
+
_tag: "Failed",
|
|
77
|
+
reason: failure.reason,
|
|
78
|
+
})));
|
|
79
|
+
if (converged._tag === "Failed") {
|
|
80
|
+
yield* status.failed(pickup.title, converged.reason);
|
|
81
|
+
yield* report({
|
|
82
|
+
pickup: pickup.id,
|
|
83
|
+
state: "failed",
|
|
84
|
+
error: converged.reason,
|
|
85
|
+
});
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
yield* log(`“${pickup.title}”: ${converged.state}`);
|
|
89
|
+
yield* report({
|
|
90
|
+
pickup: pickup.id,
|
|
91
|
+
state: converged.state,
|
|
92
|
+
codingThread: converged.thread,
|
|
93
|
+
link: converged.link,
|
|
94
|
+
...(messages.length > 0 && {
|
|
95
|
+
delivered: messages.map(({ id }) => id),
|
|
96
|
+
}),
|
|
97
|
+
});
|
|
98
|
+
}).pipe(Effect.catch((error) => status.failed(pickup.title, `Appsdoor didn't take the report: ${messageOf(error)}`)));
|
|
99
|
+
/** Brings every Pickup along, then keeps exactly the running threads' replies watched. */
|
|
100
|
+
const follow = (pickups) => Effect.gen(function* () {
|
|
101
|
+
for (const pickup of pickups)
|
|
102
|
+
yield* work(pickup);
|
|
103
|
+
const running = new Map(pickups.flatMap((pickup) => pickup.wanted === "running" && pickup.codingThread !== null
|
|
104
|
+
? [[pickup.codingThread, pickup]]
|
|
105
|
+
: []));
|
|
106
|
+
for (const thread of [...watchers.keys()])
|
|
107
|
+
if (!running.has(thread))
|
|
108
|
+
yield* unwatch(thread);
|
|
109
|
+
for (const [thread, pickup] of running)
|
|
110
|
+
yield* watch(pickup, thread);
|
|
111
|
+
yield* status.pickups(pickups.map((pickup) => ({
|
|
112
|
+
card: pickup.title,
|
|
113
|
+
state: pickup.state,
|
|
114
|
+
thread: pickup.codingThread,
|
|
115
|
+
})));
|
|
116
|
+
});
|
|
117
|
+
yield* status.pickups([]);
|
|
118
|
+
yield* log(`${config.name} works for ${config.workspace.name} with ${[
|
|
119
|
+
...harnesses.values(),
|
|
120
|
+
]
|
|
121
|
+
.map(({ name }) => name)
|
|
122
|
+
.join(", ")}.`);
|
|
123
|
+
let since;
|
|
124
|
+
let backoff = Duration.seconds(1);
|
|
125
|
+
let unreachable = false;
|
|
126
|
+
while (true) {
|
|
127
|
+
const polled = yield* Channel.work(config.api, key, since).pipe(Effect.map((answer) => ({ _tag: "Work", answer })), Effect.catch((error) => Effect.succeed(error)));
|
|
128
|
+
if (polled._tag === "Unpaired") {
|
|
129
|
+
yield* status.connected(false);
|
|
130
|
+
yield* status.failed(null, removedMessage);
|
|
131
|
+
return "unpaired";
|
|
132
|
+
}
|
|
133
|
+
if (polled._tag !== "Work") {
|
|
134
|
+
yield* status.connected(false);
|
|
135
|
+
// A refusal, such as an app too old to serve, says why itself.
|
|
136
|
+
if (!unreachable)
|
|
137
|
+
yield* status.failed(null, polled._tag === "Refused"
|
|
138
|
+
? messageOf(polled)
|
|
139
|
+
: `Appsdoor can't be reached: ${messageOf(polled)}`);
|
|
140
|
+
unreachable = true;
|
|
141
|
+
yield* Effect.sleep(backoff);
|
|
142
|
+
backoff = Duration.min(Duration.times(backoff, 2), longestBackoff);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (unreachable)
|
|
146
|
+
yield* log("Appsdoor is reachable again.");
|
|
147
|
+
unreachable = false;
|
|
148
|
+
backoff = Duration.seconds(1);
|
|
149
|
+
yield* status.connected(true);
|
|
150
|
+
since = polled.answer.version;
|
|
151
|
+
yield* follow(polled.answer.pickups);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
const messageOf = (error) => {
|
|
155
|
+
switch (error._tag) {
|
|
156
|
+
case "Unpaired":
|
|
157
|
+
return removedMessage;
|
|
158
|
+
case "Unreachable":
|
|
159
|
+
return error.reason;
|
|
160
|
+
case "Refused":
|
|
161
|
+
return error.message;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
export { removedMessage };
|
package/dist/Notify.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { runCommand } from "./command.js";
|
|
3
|
+
import { readJson, writeJson } from "./Home.js";
|
|
4
|
+
const intoFile = process.env.APPSDOOR_LAPTOP_HARNESS === "fake";
|
|
5
|
+
const appleScriptString = (value) => `"${value.replace(/["\\]/g, "\\$&")}"`;
|
|
6
|
+
/** Shows the notification; never fails, since it only ever reports another failure. */
|
|
7
|
+
export const notify = (notification) => intoFile
|
|
8
|
+
? Effect.gen(function* () {
|
|
9
|
+
const shown = (yield* readJson("notifications.json")) ?? [];
|
|
10
|
+
yield* writeJson("notifications.json", [...shown, notification]);
|
|
11
|
+
})
|
|
12
|
+
: runCommand("osascript", [
|
|
13
|
+
"-e",
|
|
14
|
+
`display notification ${appleScriptString(notification.message)} with title ${appleScriptString(notification.title)}`,
|
|
15
|
+
]).pipe(Effect.asVoid);
|
package/dist/Secrets.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { runCommand } from "./command.js";
|
|
4
|
+
import { homeFile, homeOverride, writeJson } from "./Home.js";
|
|
5
|
+
const service = "io.appsdoor.laptop";
|
|
6
|
+
const inKeychain = homeOverride === undefined;
|
|
7
|
+
const quoted = (value) => `"${value.replace(/["\\]/g, "\\$&")}"`;
|
|
8
|
+
/** Saves the secret, replacing the old one. */
|
|
9
|
+
export const saveSecret = (name, value) => inKeychain
|
|
10
|
+
? Effect.gen(function* () {
|
|
11
|
+
// `security -i` reads the command from stdin, so the secret never shows in `ps`.
|
|
12
|
+
const ran = yield* runCommand("security", ["-i"], {
|
|
13
|
+
input: `add-generic-password -U -s ${service} -a ${name} -w ${quoted(value)}\n`,
|
|
14
|
+
});
|
|
15
|
+
if (ran.code !== 0)
|
|
16
|
+
return yield* Effect.die(new Error(`The keychain refused the ${name}: ${ran.stderr.trim()}`));
|
|
17
|
+
})
|
|
18
|
+
: writeJson(name, value, 0o600);
|
|
19
|
+
/** The secret, or `undefined` when none was saved. */
|
|
20
|
+
export const readSecret = (name) => inKeychain
|
|
21
|
+
? runCommand("security", [
|
|
22
|
+
"find-generic-password",
|
|
23
|
+
"-s",
|
|
24
|
+
service,
|
|
25
|
+
"-a",
|
|
26
|
+
name,
|
|
27
|
+
"-w",
|
|
28
|
+
]).pipe(Effect.map((ran) => ran.code === 0 && ran.stdout.trim() !== ""
|
|
29
|
+
? ran.stdout.trim()
|
|
30
|
+
: undefined))
|
|
31
|
+
: Effect.promise(async () => {
|
|
32
|
+
try {
|
|
33
|
+
return JSON.parse(await readFile(homeFile(name), "utf8"));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
});
|
package/dist/Setup.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { hostname } from "node:os";
|
|
3
|
+
import { Console, Effect } from "effect";
|
|
4
|
+
import * as Channel from "./Channel.js";
|
|
5
|
+
import { runCommand } from "./command.js";
|
|
6
|
+
import { harnessesOf, homeOverride, readConfig, writeConfig } from "./Home.js";
|
|
7
|
+
import { adapters } from "./harness/index.js";
|
|
8
|
+
import { serviceEntry } from "./Install.js";
|
|
9
|
+
import { installService } from "./Launchd.js";
|
|
10
|
+
import { saveSecret } from "./Secrets.js";
|
|
11
|
+
/** A setup that can't go on, said to the member as is. */
|
|
12
|
+
export class SetupFailed extends Error {
|
|
13
|
+
}
|
|
14
|
+
const parseFolder = (given) => {
|
|
15
|
+
const split = given.indexOf("=");
|
|
16
|
+
const board = given.slice(0, split).trim();
|
|
17
|
+
const path = given.slice(split + 1).trim();
|
|
18
|
+
if (split <= 0 || board === "" || !/^(~\/|\/)/.test(path))
|
|
19
|
+
throw new SetupFailed(`--folder takes "<board name>=<folder>", the folder starting with ~/ or /: ${given}`);
|
|
20
|
+
return { board, path };
|
|
21
|
+
};
|
|
22
|
+
const pollEvery = "2 seconds";
|
|
23
|
+
/**
|
|
24
|
+
* Which Mac this is, as Appsdoor tells laptops apart: a hash of its
|
|
25
|
+
* hardware UUID (never the UUID itself), and of the state directory when
|
|
26
|
+
* `APPSDOOR_LAPTOP_HOME` sets one, so each e2e laptop is its own.
|
|
27
|
+
*/
|
|
28
|
+
const machineId = Effect.gen(function* () {
|
|
29
|
+
const ran = yield* runCommand("ioreg", [
|
|
30
|
+
"-rd1",
|
|
31
|
+
"-c",
|
|
32
|
+
"IOPlatformExpertDevice",
|
|
33
|
+
]);
|
|
34
|
+
const uuid = /"IOPlatformUUID" = "([^"]+)"/.exec(ran.stdout)?.[1] ?? hostname();
|
|
35
|
+
return createHash("sha256")
|
|
36
|
+
.update(`${uuid}\n${homeOverride ?? ""}`)
|
|
37
|
+
.digest("base64url");
|
|
38
|
+
});
|
|
39
|
+
export const setup = (options) => Effect.gen(function* () {
|
|
40
|
+
const folders = yield* Effect.try({
|
|
41
|
+
try: () => options.folders.map(parseFolder),
|
|
42
|
+
catch: (error) => error,
|
|
43
|
+
});
|
|
44
|
+
const adapter = adapters[options.harness];
|
|
45
|
+
yield* adapter.prepare.pipe(Effect.mapError((failure) => new SetupFailed(failure.reason)));
|
|
46
|
+
const unreachable = (error) => new SetupFailed(error._tag === "Unreachable"
|
|
47
|
+
? `Appsdoor can't be reached at ${options.api}: ${error.reason}`
|
|
48
|
+
: error._tag === "Refused"
|
|
49
|
+
? error.message
|
|
50
|
+
: "Appsdoor refused this laptop.");
|
|
51
|
+
const started = yield* Channel.pair(options.api, {
|
|
52
|
+
name: options.name,
|
|
53
|
+
harness: adapter.kind,
|
|
54
|
+
machine: yield* machineId,
|
|
55
|
+
version: options.version,
|
|
56
|
+
folders,
|
|
57
|
+
}).pipe(Effect.mapError(unreachable));
|
|
58
|
+
if (started._tag !== "Started")
|
|
59
|
+
return yield* Effect.fail(new SetupFailed("Appsdoor gave no pairing code."));
|
|
60
|
+
const approveAt = `${options.api}/connect-laptop?code=${started.code}`;
|
|
61
|
+
yield* Console.log(`Approve ${options.name} in Appsdoor: your browser opens on it. Its code is ${started.code}; it expires in 10 minutes.`);
|
|
62
|
+
yield* Console.log(`If the browser didn't open: ${approveAt}`);
|
|
63
|
+
if (options.browser)
|
|
64
|
+
yield* runCommand("open", [approveAt]);
|
|
65
|
+
while (true) {
|
|
66
|
+
yield* Effect.sleep(pollEvery);
|
|
67
|
+
const answer = yield* Channel.pair(options.api, {
|
|
68
|
+
secret: started.secret,
|
|
69
|
+
}).pipe(
|
|
70
|
+
// A dropped poll is tried again; the code lives for 10 minutes.
|
|
71
|
+
Effect.catchTag("Unreachable", () => Effect.succeed({ _tag: "Waiting" })), Effect.mapError(unreachable));
|
|
72
|
+
if (answer._tag === "Waiting" || answer._tag === "Started")
|
|
73
|
+
continue;
|
|
74
|
+
if (answer._tag === "Expired")
|
|
75
|
+
return yield* Effect.fail(new SetupFailed("The pairing code expired. Run appsdoor-laptop setup again."));
|
|
76
|
+
yield* saveSecret("key", answer.key);
|
|
77
|
+
// The same laptop paired again keeps the harnesses set up before.
|
|
78
|
+
const before = yield* readConfig;
|
|
79
|
+
const kept = before !== undefined &&
|
|
80
|
+
before.api === options.api &&
|
|
81
|
+
before.laptop.id === answer.laptop.id
|
|
82
|
+
? harnessesOf(before).filter((id) => id !== options.harness)
|
|
83
|
+
: [];
|
|
84
|
+
yield* writeConfig({
|
|
85
|
+
api: options.api,
|
|
86
|
+
name: answer.laptop.name,
|
|
87
|
+
harnesses: [...kept, options.harness],
|
|
88
|
+
laptop: answer.laptop,
|
|
89
|
+
workspace: answer.workspace,
|
|
90
|
+
});
|
|
91
|
+
yield* Console.log(`Paired ${answer.laptop.name} with ${answer.workspace.name}.`);
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
if (options.service) {
|
|
95
|
+
const entry = yield* serviceEntry(options.entry, options.version).pipe(Effect.mapError((failure) => new SetupFailed(failure.message)));
|
|
96
|
+
const plist = yield* installService(entry);
|
|
97
|
+
yield* Console.log(`Installed the background service (${plist}); it starts at login.`);
|
|
98
|
+
}
|
|
99
|
+
yield* Console.log("Paired.");
|
|
100
|
+
});
|
package/dist/Status.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { appendFile, mkdir } from "node:fs/promises";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { home, logFile, writeJson } from "./Home.js";
|
|
4
|
+
import { notify } from "./Notify.js";
|
|
5
|
+
/*
|
|
6
|
+
* What the running laptop app knows about itself, kept in
|
|
7
|
+
* `<home>/status.json` for `appsdoor-laptop status`, and its log in
|
|
8
|
+
* `<home>/laptop.log` for `appsdoor-laptop logs`. Every failure goes
|
|
9
|
+
* through `failed`: it is logged, kept for `status`, and notified.
|
|
10
|
+
*/
|
|
11
|
+
const keptErrors = 50;
|
|
12
|
+
/** Writes a timestamped line to stdout and the log file. */
|
|
13
|
+
export const log = (line) => Effect.promise(async () => {
|
|
14
|
+
const stamped = `${new Date().toISOString()} ${line}`;
|
|
15
|
+
console.log(stamped);
|
|
16
|
+
await mkdir(home, { recursive: true, mode: 0o700 });
|
|
17
|
+
await appendFile(logFile, `${stamped}\n`);
|
|
18
|
+
});
|
|
19
|
+
export const makeStatus = () => {
|
|
20
|
+
let status = { connected: false, pickups: [], errors: [] };
|
|
21
|
+
const save = () => writeJson("status.json", status);
|
|
22
|
+
return {
|
|
23
|
+
connected: (connected) => Effect.gen(function* () {
|
|
24
|
+
if (status.connected === connected)
|
|
25
|
+
return;
|
|
26
|
+
status = { ...status, connected };
|
|
27
|
+
yield* save();
|
|
28
|
+
}),
|
|
29
|
+
pickups: (pickups) => Effect.gen(function* () {
|
|
30
|
+
status = { ...status, pickups };
|
|
31
|
+
yield* save();
|
|
32
|
+
}),
|
|
33
|
+
/** Records a failure, about a card (its title) or the laptop itself, and tells the member. */
|
|
34
|
+
failed: (card, message) => Effect.gen(function* () {
|
|
35
|
+
const at = new Date().toISOString();
|
|
36
|
+
status = {
|
|
37
|
+
...status,
|
|
38
|
+
errors: [...status.errors, { at, card, message }].slice(-keptErrors),
|
|
39
|
+
};
|
|
40
|
+
yield* save();
|
|
41
|
+
yield* log(`Failed${card === null ? "" : ` on “${card}”`}: ${message}`);
|
|
42
|
+
yield* notify({
|
|
43
|
+
title: card === null ? "Appsdoor laptop" : `Appsdoor: ${card}`,
|
|
44
|
+
message,
|
|
45
|
+
});
|
|
46
|
+
}),
|
|
47
|
+
};
|
|
48
|
+
};
|
package/dist/Version.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
/*
|
|
3
|
+
* The laptop app's version, from its package.json: one folder up from
|
|
4
|
+
* this file both in `src` (a checkout) and in `dist` (the published
|
|
5
|
+
* package). Pairing and every call to Appsdoor name it.
|
|
6
|
+
*/
|
|
7
|
+
export const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
package/dist/command.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
/**
|
|
4
|
+
* Runs `file` with `args` to the end, never failing: a program that is
|
|
5
|
+
* missing or exits non-zero answers its code. `input` goes to its stdin,
|
|
6
|
+
* which keeps secrets off the command line. It is stopped after
|
|
7
|
+
* `timeoutMs`, 30 seconds unless said.
|
|
8
|
+
*/
|
|
9
|
+
export const runCommand = (file, args, options = {}) => Effect.callback((resume) => {
|
|
10
|
+
const child = execFile(file, [...args], { timeout: options.timeoutMs ?? 30_000, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
11
|
+
const code = error === null
|
|
12
|
+
? 0
|
|
13
|
+
: typeof error.code === "number"
|
|
14
|
+
? error.code
|
|
15
|
+
: null;
|
|
16
|
+
resume(Effect.succeed({
|
|
17
|
+
code,
|
|
18
|
+
stdout,
|
|
19
|
+
stderr: stderr || (error?.message ?? ""),
|
|
20
|
+
}));
|
|
21
|
+
});
|
|
22
|
+
child.stdin?.end(options.input ?? "");
|
|
23
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Context, Data } from "effect";
|
|
2
|
+
/** The harness couldn't do what was asked; `reason` is shown to the member as is. */
|
|
3
|
+
export class HarnessFailed extends Data.TaggedError("HarnessFailed") {
|
|
4
|
+
}
|
|
5
|
+
export class Harness extends Context.Service()("laptop/Harness") {
|
|
6
|
+
}
|
|
7
|
+
/** "Continue." is what a stopped coding thread is sent when it continues with no comment waiting. */
|
|
8
|
+
export const continueMessage = "Continue.";
|