appsdoor-laptop 0.0.0-stage → 0.2.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.
@@ -0,0 +1,145 @@
1
+ import { getSessionInfo, query, } from "@anthropic-ai/claude-agent-sdk";
2
+ import { Effect, Layer, Queue, Stream } from "effect";
3
+ import { continueMessage, Harness, HarnessFailed, waiting, working, } from "./Harness.js";
4
+ const userMessage = (text) => ({
5
+ type: "user",
6
+ message: { role: "user", content: text },
7
+ parent_tool_use_id: null,
8
+ });
9
+ /** An input stream the session reads from as messages are pushed. */
10
+ const inbox = () => {
11
+ const waiting = [];
12
+ let wake;
13
+ let ended = false;
14
+ const messages = {
15
+ async *[Symbol.asyncIterator]() {
16
+ while (true) {
17
+ const next = waiting.shift();
18
+ if (next !== undefined) {
19
+ yield next;
20
+ continue;
21
+ }
22
+ if (ended)
23
+ return;
24
+ await new Promise((resolve) => {
25
+ wake = resolve;
26
+ });
27
+ }
28
+ },
29
+ };
30
+ return {
31
+ messages,
32
+ push: (text) => {
33
+ waiting.push(userMessage(text));
34
+ wake?.();
35
+ },
36
+ end: () => {
37
+ ended = true;
38
+ wake?.();
39
+ },
40
+ };
41
+ };
42
+ const failed = (error) => new HarnessFailed({
43
+ reason: `Claude Code couldn't do it: ${error instanceof Error ? error.message : String(error)}`,
44
+ });
45
+ export const ClaudeCodeHarness = Layer.effect(Harness, Effect.gen(function* () {
46
+ const sessions = new Map();
47
+ const turnQueues = new Map();
48
+ const queueOf = (thread) => Effect.gen(function* () {
49
+ const known = turnQueues.get(thread);
50
+ if (known !== undefined)
51
+ return known;
52
+ const queue = yield* Queue.unbounded();
53
+ turnQueues.set(thread, queue);
54
+ return queue;
55
+ });
56
+ /** Opens the session, new or resumed, and reads its turns in the background. */
57
+ const open = (thread, folder, resume) => Effect.gen(function* () {
58
+ const input = inbox();
59
+ const running = query({
60
+ prompt: input.messages,
61
+ options: {
62
+ cwd: folder,
63
+ ...(resume ? { resume: thread } : { sessionId: thread }),
64
+ },
65
+ });
66
+ const session = { query: running, push: input.push, end: input.end };
67
+ sessions.set(thread, session);
68
+ const turns = yield* queueOf(thread);
69
+ // A turn starts with its first message and ends with its result;
70
+ // only a successful one leaves the thread waiting.
71
+ let busy = false;
72
+ yield* Stream.fromAsyncIterable(running, failed).pipe(Stream.runForEach((message) => {
73
+ if (message.type !== "result") {
74
+ if (busy)
75
+ return Effect.void;
76
+ busy = true;
77
+ return Queue.offer(turns, working);
78
+ }
79
+ busy = false;
80
+ return message.subtype === "success" && !message.is_error
81
+ ? Queue.offer(turns, waiting(message.result))
82
+ : Effect.void;
83
+ }), Effect.ignore, Effect.ensuring(Effect.sync(() => {
84
+ if (sessions.get(thread) === session)
85
+ sessions.delete(thread);
86
+ })), Effect.forkDetach);
87
+ return session;
88
+ });
89
+ const stop = (thread) => Effect.gen(function* () {
90
+ const session = sessions.get(thread);
91
+ if (session === undefined)
92
+ return;
93
+ sessions.delete(thread);
94
+ yield* Effect.tryPromise({
95
+ try: () => session.query.interrupt(),
96
+ catch: failed,
97
+ }).pipe(Effect.ignore);
98
+ session.end();
99
+ session.query.close();
100
+ });
101
+ const start = (run) => Effect.gen(function* () {
102
+ const thread = run.runId;
103
+ const existing = yield* Effect.tryPromise({
104
+ try: () => getSessionInfo(thread, { dir: run.folder }),
105
+ catch: failed,
106
+ });
107
+ const session = sessions.get(thread) ??
108
+ (yield* open(thread, run.folder, existing !== undefined));
109
+ if (existing === undefined)
110
+ session.push(run.prompt);
111
+ for (const message of run.messages)
112
+ session.push(message);
113
+ return { thread, link: null, state: "running" };
114
+ });
115
+ return Harness.of({
116
+ name: "Claude Code",
117
+ health: Effect.succeed({ _tag: "Ready" }),
118
+ converge: (run) => Effect.gen(function* () {
119
+ const { thread } = run;
120
+ if (thread === null && run.want === "running")
121
+ return yield* start(run);
122
+ if (thread === null)
123
+ return {
124
+ thread: null,
125
+ link: null,
126
+ state: run.want === "closed" ? "finished" : "stopped",
127
+ };
128
+ if (run.want !== "running") {
129
+ yield* stop(thread);
130
+ return {
131
+ thread,
132
+ link: null,
133
+ state: run.want === "closed" ? "finished" : "stopped",
134
+ };
135
+ }
136
+ const session = sessions.get(thread) ?? (yield* open(thread, run.folder, true));
137
+ for (const message of run.messages.length === 0
138
+ ? [continueMessage]
139
+ : run.messages)
140
+ session.push(message);
141
+ return { thread, link: null, state: "running" };
142
+ }),
143
+ turns: (thread) => Stream.unwrap(Effect.map(queueOf(thread), Stream.fromQueue)),
144
+ });
145
+ }));
@@ -0,0 +1,141 @@
1
+ import { Codex } from "@openai/codex-sdk";
2
+ import { Deferred, Effect, Layer, Queue, Stream } from "effect";
3
+ import { runCommand } from "../command.js";
4
+ import { readJson, writeJson } from "../Home.js";
5
+ import { continueMessage, Harness, HarnessFailed, waiting, working, } from "./Harness.js";
6
+ /*
7
+ * Codex through `@openai/codex-sdk`. Codex names its own threads, so the
8
+ * thread each Pickup started is remembered in `<home>/codex-threads.json`
9
+ * as soon as Codex names it: a repeated start resumes it. Turns run one
10
+ * after another; stopping aborts the current one and drops the rest, and
11
+ * closing also runs `codex archive`. Permissions are whatever the member's
12
+ * Codex config gives.
13
+ */
14
+ const threadsFile = "codex-threads.json";
15
+ const failed = (error) => new HarnessFailed({
16
+ reason: `Codex couldn't do it: ${error instanceof Error ? error.message : String(error)}`,
17
+ });
18
+ export const CodexHarness = Layer.effect(Harness, Effect.gen(function* () {
19
+ const codex = new Codex();
20
+ const live = new Map();
21
+ const turnQueues = new Map();
22
+ const queueOf = (thread) => Effect.gen(function* () {
23
+ const known = turnQueues.get(thread);
24
+ if (known !== undefined)
25
+ return known;
26
+ const queue = yield* Queue.unbounded();
27
+ turnQueues.set(thread, queue);
28
+ return queue;
29
+ });
30
+ /**
31
+ * Runs one turn after the ones already queued on `session`; `named` hears
32
+ * the thread's id once Codex gives it. The final agent message of a
33
+ * completed turn becomes its reply.
34
+ */
35
+ const queueTurn = (session, text, named) => {
36
+ session.turns = session.turns
37
+ .then(async () => {
38
+ if (session.abort.signal.aborted)
39
+ return;
40
+ const { events } = await session.thread.runStreamed(text, {
41
+ signal: session.abort.signal,
42
+ });
43
+ let last = null;
44
+ const tell = (turn) => {
45
+ const id = session.thread.id;
46
+ if (id !== null)
47
+ Effect.runSync(Queue.offer(Effect.runSync(queueOf(id)), turn));
48
+ };
49
+ for await (const event of events) {
50
+ if (event.type === "thread.started")
51
+ named(event.thread_id);
52
+ if (event.type === "turn.started")
53
+ tell(working);
54
+ if (event.type === "item.completed" &&
55
+ event.item.type === "agent_message")
56
+ last = event.item.text;
57
+ if (event.type === "turn.completed")
58
+ tell(waiting(last));
59
+ }
60
+ })
61
+ .catch(() => {
62
+ // An aborted or failed turn leaves no reply; the next turn still runs.
63
+ });
64
+ };
65
+ const sessionOf = (thread, folder) => {
66
+ const known = live.get(thread);
67
+ if (known !== undefined)
68
+ return known;
69
+ const session = {
70
+ thread: codex.resumeThread(thread, { workingDirectory: folder }),
71
+ abort: new AbortController(),
72
+ turns: Promise.resolve(),
73
+ };
74
+ live.set(thread, session);
75
+ return session;
76
+ };
77
+ const start = (run) => Effect.gen(function* () {
78
+ const remembered = (yield* readJson(threadsFile)) ?? {};
79
+ const known = remembered[run.runId];
80
+ if (known !== undefined) {
81
+ const session = sessionOf(known, run.folder);
82
+ for (const message of run.messages)
83
+ queueTurn(session, message, () => { });
84
+ return { thread: known, link: null, state: "running" };
85
+ }
86
+ const named = yield* Deferred.make();
87
+ const session = {
88
+ thread: codex.startThread({ workingDirectory: run.folder }),
89
+ abort: new AbortController(),
90
+ turns: Promise.resolve(),
91
+ };
92
+ queueTurn(session, run.prompt, (id) => Effect.runSync(Deferred.succeed(named, id)));
93
+ // A turn that ends without naming its thread failed to start.
94
+ session.turns.then(() => Effect.runSync(Deferred.fail(named, new HarnessFailed({ reason: "Codex didn't start a thread." }))));
95
+ const thread = yield* Deferred.await(named);
96
+ live.set(thread, session);
97
+ yield* writeJson(threadsFile, { ...remembered, [run.runId]: thread });
98
+ for (const message of run.messages)
99
+ queueTurn(session, message, () => { });
100
+ return { thread, link: null, state: "running" };
101
+ });
102
+ const stop = (thread) => Effect.sync(() => {
103
+ live.get(thread)?.abort.abort();
104
+ live.delete(thread);
105
+ });
106
+ return Harness.of({
107
+ name: "Codex",
108
+ health: Effect.succeed({ _tag: "Ready" }),
109
+ converge: (run) => Effect.gen(function* () {
110
+ const { thread } = run;
111
+ if (thread === null && run.want === "running")
112
+ return yield* start(run);
113
+ if (thread === null)
114
+ return {
115
+ thread: null,
116
+ link: null,
117
+ state: run.want === "closed" ? "finished" : "stopped",
118
+ };
119
+ if (run.want === "running") {
120
+ const session = sessionOf(thread, run.folder);
121
+ for (const message of run.messages.length === 0
122
+ ? [continueMessage]
123
+ : run.messages)
124
+ queueTurn(session, message, () => { });
125
+ return { thread, link: null, state: "running" };
126
+ }
127
+ yield* stop(thread);
128
+ if (run.want === "closed") {
129
+ const archived = yield* runCommand("codex", ["archive", thread]);
130
+ if (archived.code !== 0)
131
+ return yield* failed(`codex archive ${thread} failed: ${archived.stderr.trim()}`);
132
+ }
133
+ return {
134
+ thread,
135
+ link: null,
136
+ state: run.want === "closed" ? "finished" : "stopped",
137
+ };
138
+ }),
139
+ turns: (thread) => Stream.unwrap(Effect.map(queueOf(thread), Stream.fromQueue)),
140
+ });
141
+ }));
@@ -0,0 +1,96 @@
1
+ import { Effect, Layer, Queue, Stream } from "effect";
2
+ import { readJson, writeJson } from "../Home.js";
3
+ import { continueMessage, Harness, HarnessFailed, waiting, working, } from "./Harness.js";
4
+ const logName = "fake-harness.json";
5
+ const failsStart = process.env.APPSDOOR_LAPTOP_FAKE_FAIL === "start";
6
+ const record = (change) => Effect.gen(function* () {
7
+ const log = (yield* readJson(logName)) ?? {
8
+ starts: [],
9
+ messages: [],
10
+ stops: [],
11
+ closes: [],
12
+ };
13
+ yield* writeJson(logName, change(log));
14
+ });
15
+ export const FakeHarness = Layer.effect(Harness, Effect.gen(function* () {
16
+ // Each message is a turn, answered at once; its events wait in the
17
+ // thread's queue until the loop reads them.
18
+ const queues = new Map();
19
+ const queueOf = (thread) => Effect.gen(function* () {
20
+ const known = queues.get(thread);
21
+ if (known !== undefined)
22
+ return known;
23
+ const queue = yield* Queue.unbounded();
24
+ queues.set(thread, queue);
25
+ return queue;
26
+ });
27
+ const turn = (thread, message) => Effect.gen(function* () {
28
+ const queue = yield* queueOf(thread);
29
+ yield* Queue.offer(queue, working);
30
+ yield* Queue.offer(queue, waiting(`Fake reply to: ${message}`));
31
+ });
32
+ const send = (thread, messages) => Effect.forEach(messages, (text) => Effect.gen(function* () {
33
+ yield* record((log) => ({
34
+ ...log,
35
+ messages: [...log.messages, { thread, text }],
36
+ }));
37
+ yield* turn(thread, text);
38
+ }), { discard: true });
39
+ const start = (run) => Effect.gen(function* () {
40
+ if (failsStart)
41
+ return yield* new HarnessFailed({
42
+ reason: "The fake harness refused to start.",
43
+ });
44
+ const thread = `fake-${run.runId}`;
45
+ yield* record((log) => ({
46
+ ...log,
47
+ starts: [
48
+ ...log.starts,
49
+ {
50
+ runId: run.runId,
51
+ folder: run.folder,
52
+ prompt: run.prompt,
53
+ thread,
54
+ },
55
+ ],
56
+ }));
57
+ yield* turn(thread, run.prompt);
58
+ yield* send(thread, run.messages);
59
+ return { thread, link: null, state: "running" };
60
+ });
61
+ return Harness.of({
62
+ name: "Fake harness",
63
+ health: Effect.succeed({ _tag: "Ready" }),
64
+ converge: (run) => Effect.gen(function* () {
65
+ const { thread } = run;
66
+ if (thread === null)
67
+ return run.want === "running"
68
+ ? yield* start(run)
69
+ : {
70
+ thread: null,
71
+ link: null,
72
+ state: run.want === "closed"
73
+ ? "finished"
74
+ : "stopped",
75
+ };
76
+ switch (run.want) {
77
+ case "running":
78
+ yield* send(thread, run.messages.length === 0 ? [continueMessage] : run.messages);
79
+ return { thread, link: null, state: "running" };
80
+ case "stopped":
81
+ yield* record((log) => ({
82
+ ...log,
83
+ stops: [...log.stops, { thread }],
84
+ }));
85
+ return { thread, link: null, state: "stopped" };
86
+ case "closed":
87
+ yield* record((log) => ({
88
+ ...log,
89
+ closes: [...log.closes, { thread }],
90
+ }));
91
+ return { thread, link: null, state: "finished" };
92
+ }
93
+ }),
94
+ turns: (thread) => Stream.unwrap(Effect.map(queueOf(thread), Stream.fromQueue)),
95
+ });
96
+ }));
@@ -0,0 +1,47 @@
1
+ import { Context, Effect, Layer } from "effect";
2
+ import { ClaudeCodeHarness } from "./claude-code.js";
3
+ import { CodexHarness } from "./codex.js";
4
+ import { FakeHarness } from "./fake.js";
5
+ import { Harness } from "./Harness.js";
6
+ import { prepareT3Code, T3CodeHarness } from "./t3code.js";
7
+ /** What `--harness` offers: `fake` only for the e2e suite. */
8
+ export const harnessIds = process.env.APPSDOOR_LAPTOP_HARNESS === "fake"
9
+ ? ["t3code", "claude-code", "codex", "fake"]
10
+ : ["t3code", "claude-code", "codex"];
11
+ export const adapters = {
12
+ t3code: {
13
+ kind: "t3Code",
14
+ name: "T3 Code",
15
+ prepare: prepareT3Code,
16
+ layer: T3CodeHarness,
17
+ },
18
+ "claude-code": {
19
+ kind: "claudeCode",
20
+ name: "Claude Code",
21
+ prepare: Effect.void,
22
+ layer: () => ClaudeCodeHarness,
23
+ },
24
+ codex: {
25
+ kind: "codex",
26
+ name: "Codex",
27
+ prepare: Effect.void,
28
+ layer: () => CodexHarness,
29
+ },
30
+ fake: {
31
+ kind: "fake",
32
+ name: "Fake harness",
33
+ prepare: Effect.void,
34
+ layer: () => FakeHarness,
35
+ },
36
+ };
37
+ /** The id `setup --harness` takes for Appsdoor's id of a harness. */
38
+ export const harnessIdOf = (kind) => Object.keys(adapters).find((id) => adapters[id].kind === kind) ?? "fake";
39
+ /** Every harness in `ids`, built for this laptop and kept for the scope, by Appsdoor's id. */
40
+ export const runHarnesses = (ids, laptopName) => Effect.gen(function* () {
41
+ const built = new Map();
42
+ for (const id of ids) {
43
+ const context = yield* Layer.build(adapters[id].layer(laptopName));
44
+ built.set(adapters[id].kind, Context.get(context, Harness));
45
+ }
46
+ return built;
47
+ });
@@ -0,0 +1,196 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import { Console, Effect } from "effect";
6
+ import { runCommand } from "../command.js";
7
+ import { readSecret, saveSecret } from "../Secrets.js";
8
+ import { HarnessFailed } from "./Harness.js";
9
+ const t3 = path.join(homedir(), ".t3/bin/t3");
10
+ export const reconnectHint = "Run appsdoor-laptop reconnect to approve Appsdoor in T3 Code again.";
11
+ /** The kept approval, unless there is none or it ran out. */
12
+ export const readApproval = Effect.gen(function* () {
13
+ const saved = yield* readSecret("t3-token");
14
+ if (saved === undefined)
15
+ return undefined;
16
+ try {
17
+ const approval = JSON.parse(saved);
18
+ return typeof approval.token === "string" &&
19
+ Date.parse(approval.expiresAt) > Date.now()
20
+ ? approval
21
+ : undefined;
22
+ }
23
+ catch {
24
+ // A token from before approvals: it never reached T3's MCP.
25
+ return undefined;
26
+ }
27
+ });
28
+ const base64url = (bytes) => bytes.toString("base64url");
29
+ const failed = (reason) => new HarnessFailed({ reason: `T3 Code's approval failed: ${reason}` });
30
+ const json = (response) => Effect.tryPromise({
31
+ try: async () => {
32
+ const body = (await response.json());
33
+ if (!response.ok)
34
+ throw new Error(String(body.error_description ?? body.error ?? response.status));
35
+ return body;
36
+ },
37
+ catch: (error) => failed(error.message),
38
+ });
39
+ const fetchJson = (url, init) => Effect.tryPromise({
40
+ try: () => fetch(url, init),
41
+ catch: (error) => failed(`${url} couldn't be reached: ${String(error)}`),
42
+ }).pipe(Effect.flatMap(json));
43
+ const page = (title, body) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font:15px system-ui;margin:15vh auto;max-width:28rem;padding:0 1rem"><h1 style="font-size:20px">${title}</h1><p>${body}</p></body>`;
44
+ /** Waits on a loopback port for T3 Code to send the browser back with a code. */
45
+ const loopback = (state) => Effect.callback((resume) => {
46
+ let answer = () => { };
47
+ let refuse = () => { };
48
+ const code = new Promise((resolve, reject) => {
49
+ answer = resolve;
50
+ refuse = reject;
51
+ });
52
+ const server = createServer((request, response) => {
53
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
54
+ if (url.pathname !== "/callback") {
55
+ response.writeHead(404).end();
56
+ return;
57
+ }
58
+ const given = url.searchParams.get("code");
59
+ const ok = given !== null && url.searchParams.get("state") === state;
60
+ response
61
+ .writeHead(ok ? 200 : 400, { "content-type": "text/html" })
62
+ .end(ok
63
+ ? page("Appsdoor is approved in T3 Code", "You can close this tab. Setup carries on in the terminal.")
64
+ : page("T3 Code didn't approve Appsdoor", url.searchParams.get("error_description") ??
65
+ "Run setup again to try once more."));
66
+ server.close();
67
+ if (ok)
68
+ answer(given);
69
+ else
70
+ refuse(new Error(url.searchParams.get("error_description") ??
71
+ url.searchParams.get("error") ??
72
+ "T3 Code answered no code."));
73
+ });
74
+ server.once("error", (error) => resume(Effect.fail(failed(error.message))));
75
+ server.listen(0, "127.0.0.1", () => {
76
+ const address = server.address();
77
+ const port = typeof address === "object" && address ? address.port : 0;
78
+ resume(Effect.succeed({
79
+ redirectUri: `http://127.0.0.1:${port}/callback`,
80
+ code,
81
+ close: () => server.close(),
82
+ }));
83
+ });
84
+ return Effect.sync(() => server.close());
85
+ });
86
+ /** Whether T3 Code still holds the sign-in link `id`, unused. */
87
+ const stillUnused = (id) => runCommand(t3, ["auth", "pairing", "list", "--json"]).pipe(Effect.map((listed) => {
88
+ try {
89
+ const active = JSON.parse(listed.stdout);
90
+ return listed.code === 0 && active.some((link) => link.id === id);
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ }));
96
+ /**
97
+ * Signs the browser in to T3 Code with a 5-minute sign-in link from
98
+ * `t3 auth pairing create`, so its approval page needs no code pasted
99
+ * (the desktop app's own sign-in isn't the browser's). The link lands on
100
+ * T3 Code's home. The approval page opens only once T3 Code used the
101
+ * link, up to 30 seconds: opened sooner, it asks for a code. Best effort.
102
+ */
103
+ const signInBrowser = (origin) => Effect.gen(function* () {
104
+ const created = yield* runCommand(t3, [
105
+ "auth",
106
+ "pairing",
107
+ "create",
108
+ "--ttl",
109
+ "5m",
110
+ "--label",
111
+ "Appsdoor laptop sign-in",
112
+ "--base-url",
113
+ origin,
114
+ "--json",
115
+ ]);
116
+ try {
117
+ const { id, pairUrl } = JSON.parse(created.stdout);
118
+ if (created.code !== 0 || typeof pairUrl !== "string")
119
+ return;
120
+ yield* runCommand("open", [pairUrl]);
121
+ for (let waited = 0; waited < 60; waited++) {
122
+ yield* Effect.sleep("500 millis");
123
+ if (id === undefined || !(yield* stillUnused(id)))
124
+ break;
125
+ }
126
+ // The signed-in page sets its session as it lands.
127
+ yield* Effect.sleep("1 second");
128
+ }
129
+ catch {
130
+ // No sign-in link: the approval page asks for a code instead.
131
+ }
132
+ });
133
+ /**
134
+ * Opens T3 Code's approval page for Appsdoor at `origin` and keeps the
135
+ * token once the member approves it. Waits up to 10 minutes.
136
+ */
137
+ export const approveInT3Code = (origin) => Effect.gen(function* () {
138
+ const server = yield* fetchJson(`${origin}/.well-known/oauth-authorization-server`);
139
+ const resource = `${origin}/mcp`;
140
+ const state = base64url(randomBytes(16));
141
+ const verifier = base64url(randomBytes(32));
142
+ const challenge = base64url(createHash("sha256").update(verifier).digest());
143
+ const { redirectUri, code } = yield* Effect.acquireRelease(loopback(state), ({ close }) => Effect.sync(close));
144
+ const client = yield* fetchJson(String(server.registration_endpoint), {
145
+ method: "POST",
146
+ headers: { "content-type": "application/json" },
147
+ body: JSON.stringify({
148
+ client_name: "Appsdoor laptop",
149
+ redirect_uris: [redirectUri],
150
+ grant_types: ["authorization_code"],
151
+ response_types: ["code"],
152
+ token_endpoint_auth_method: "none",
153
+ }),
154
+ });
155
+ const authorize = new URL(String(server.authorization_endpoint));
156
+ for (const [key, value] of Object.entries({
157
+ response_type: "code",
158
+ client_id: String(client.client_id),
159
+ redirect_uri: redirectUri,
160
+ code_challenge: challenge,
161
+ code_challenge_method: "S256",
162
+ state,
163
+ resource,
164
+ scope: "orchestration:read orchestration:operate",
165
+ }))
166
+ authorize.searchParams.set(key, value);
167
+ yield* Console.log("Approve Appsdoor in T3 Code: choose Full access, so Appsdoor can stop and archive the threads it starts.");
168
+ yield* Console.log(`If the browser didn't open: ${authorize.href}`);
169
+ yield* signInBrowser(origin);
170
+ yield* runCommand("open", [authorize.href]);
171
+ const given = yield* Effect.tryPromise({
172
+ try: () => code,
173
+ catch: (error) => failed(error.message),
174
+ }).pipe(Effect.timeoutOrElse({
175
+ duration: "10 minutes",
176
+ orElse: () => Effect.fail(failed("nobody approved it within 10 minutes.")),
177
+ }));
178
+ const token = yield* fetchJson(String(server.token_endpoint), {
179
+ method: "POST",
180
+ headers: { "content-type": "application/x-www-form-urlencoded" },
181
+ body: new URLSearchParams({
182
+ grant_type: "authorization_code",
183
+ code: given,
184
+ redirect_uri: redirectUri,
185
+ client_id: String(client.client_id),
186
+ code_verifier: verifier,
187
+ resource,
188
+ }),
189
+ });
190
+ const approval = {
191
+ token: String(token.access_token),
192
+ expiresAt: new Date(Date.now() + Number(token.expires_in ?? 0) * 1000).toISOString(),
193
+ };
194
+ yield* saveSecret("t3-token", JSON.stringify(approval));
195
+ return approval;
196
+ }).pipe(Effect.scoped);