@impact-ai/setup 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/src/main.js ADDED
@@ -0,0 +1,562 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ // npx @impact-ai/setup, run in an application's folder: checks that it may go on, signs in through the browser, writes
4
+ // one ingest key to .env, hands one task to the coding agent on this computer, runs the application once, and finishes
5
+ // when impact.ai has received and checked its trace. The ingest key goes to .env and to the run's environment only:
6
+ // never to the terminal, the agent's task, a log or a commit.
7
+ //
8
+ // Ends: 0 checked; 3 set up, but no checked trace in time (or impact.ai could not be reached while waiting); 1 failed
9
+ // (not allowed, stopped, the agent failed, the run failed); 2 usage.
10
+
11
+ import path from "node:path";
12
+ import { VERSION, UsageError, parse, usage } from "./args.js";
13
+ import { AGENTS, composePrompt, findAgent, invocation, parseReply } from "./agents.js";
14
+ import { ENDPOINT, KEY, ensureIgnored, holdsKey, readEnvValues, writeEnv } from "./dotenv.js";
15
+ import { openBrowser, start } from "./processes.js";
16
+ import {
17
+ computerName,
18
+ detectLanguage,
19
+ folderName,
20
+ gitIgnores,
21
+ gitState,
22
+ headMoved,
23
+ uncommittedFiles,
24
+ } from "./project.js";
25
+ import { Service } from "./service.js";
26
+ import { Terminal } from "./terminal.js";
27
+
28
+ export const EXIT = { checked: 0, failed: 1, usage: 2, unchecked: 3 };
29
+
30
+ // The protocol's times, in seconds.
31
+ const ALLOW_WINDOW = 10 * 60; // a setup lives 10 minutes until allowed
32
+ const TRACE_WINDOW = 15 * 60; // the command waits for a checked trace at most 15 minutes after the run starts
33
+ const STATUS_EVERY = 3;
34
+ const SLOW_DOWN = 5;
35
+ const RUN_GRACE = 10; // after a run that failed, how long a trace it sent before failing may take to arrive
36
+
37
+ const STEP_NAMES = { "signed-in": "Signed in", instrumented: "Instrumented", running: "Running" };
38
+
39
+ /** The command has said how it ended; `code` is its exit code. */
40
+ class Ended extends Error {
41
+ constructor(code) {
42
+ super(`ended with ${code}`);
43
+ this.code = code;
44
+ }
45
+ }
46
+
47
+ function clip(text, max = 200) {
48
+ const flat = String(text).replace(/\s+/g, " ").trim();
49
+ return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
50
+ }
51
+
52
+ /** HH:MM in the computer's time zone. */
53
+ export function clock(at) {
54
+ const date = new Date(at);
55
+ if (Number.isNaN(date.getTime())) return "--:--";
56
+ return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
57
+ }
58
+
59
+ function sleep(ms) {
60
+ return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
61
+ }
62
+
63
+ function isAddress(value) {
64
+ try {
65
+ const url = new URL(value);
66
+ return url.protocol === "https:" || (url.protocol === "http:" && /^(?:localhost|127(?:\.\d+){3}|\[::1\])$/.test(url.hostname));
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+
72
+ /** The environment without the setup's variables: the agent never holds the key. */
73
+ function withoutKeys(env) {
74
+ const copy = { ...env };
75
+ delete copy[KEY];
76
+ delete copy[ENDPOINT];
77
+ return copy;
78
+ }
79
+
80
+ /** Whether an address is on the origin the command was given: the only one it opens in a browser. */
81
+ function sameOrigin(address, origin) {
82
+ try {
83
+ return new URL(address).origin === origin;
84
+ } catch {
85
+ return false;
86
+ }
87
+ }
88
+
89
+ export function describeTrace(trace) {
90
+ const captured =
91
+ trace.captured === "full"
92
+ ? "message text captured"
93
+ : trace.captured === "metadata"
94
+ ? "metadata only"
95
+ : trace.captured
96
+ ? `${trace.captured} captured`
97
+ : "";
98
+ const what = [trace.operation, trace.environment ? `in ${trace.environment}` : ""].filter(Boolean).join(" ");
99
+ return `Trace received at ${clock(trace.at)} from ${trace.service || "the application"}${what ? `: ${what}` : ""}${
100
+ captured ? `, ${captured}` : ""
101
+ }.`;
102
+ }
103
+
104
+ export function describeChecked(checked) {
105
+ const count = Number(checked.checks) || 0;
106
+ const flagged = Array.isArray(checked.flagged) ? checked.flagged.filter((name) => typeof name === "string") : [];
107
+ const ran = `${count} ${count === 1 ? "check" : "checks"} ran`;
108
+ return `Checked: ${ran}, ${flagged.length ? `flagged: ${flagged.join(", ")}` : "nothing flagged"}`;
109
+ }
110
+
111
+ function contentLine(product) {
112
+ if (product?.contentMode === "full") return "Message text is sent: this Product keeps full content.";
113
+ if (product?.contentMode === "metadata") return "Message text stays out: this Product keeps metadata only.";
114
+ return null;
115
+ }
116
+
117
+ /**
118
+ * Run the command.
119
+ * @param {string[]} argv
120
+ * @param {{ env?: Record<string, string | undefined>, cwd?: string, stdin?: NodeJS.ReadableStream,
121
+ * stdout?: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, second?: number, fetch?: typeof fetch,
122
+ * signals?: NodeJS.EventEmitter | null, exit?: (code: number) => void }} [context]
123
+ * `second` is how many milliseconds a second of the protocol lasts: 1000, except in tests.
124
+ * @returns {Promise<number>} the exit code
125
+ */
126
+ export async function main(argv, context = {}) {
127
+ const ctx = {
128
+ env: context.env ?? process.env,
129
+ cwd: context.cwd ?? process.cwd(),
130
+ stdin: context.stdin ?? process.stdin,
131
+ stdout: context.stdout ?? process.stdout,
132
+ stderr: context.stderr ?? process.stderr,
133
+ second: context.second ?? 1000,
134
+ fetch: context.fetch ?? globalThis.fetch,
135
+ signals: context.signals === undefined ? process : context.signals,
136
+ exit: context.exit ?? ((code) => process.exit(code)),
137
+ };
138
+ let options;
139
+ try {
140
+ options = parse(argv, ctx.env);
141
+ } catch (error) {
142
+ if (!(error instanceof UsageError)) throw error;
143
+ ctx.stderr.write(`${error.message}\nRun npx @impact-ai/setup --help for the options.\n`);
144
+ return EXIT.usage;
145
+ }
146
+ if (options.help) {
147
+ ctx.stdout.write(usage());
148
+ return EXIT.checked;
149
+ }
150
+ if (options.version) {
151
+ ctx.stdout.write(`${VERSION}\n`);
152
+ return EXIT.checked;
153
+ }
154
+ return new Setup(options, ctx).run();
155
+ }
156
+
157
+ class Setup {
158
+ constructor(options, ctx) {
159
+ this.options = options;
160
+ this.ctx = ctx;
161
+ this.folder = path.resolve(ctx.cwd);
162
+ this.say = new Terminal({ stdin: ctx.stdin, stdout: ctx.stdout, stderr: ctx.stderr, yes: options.yes });
163
+ this.service = new Service(options.origin, { fetch: ctx.fetch });
164
+ /** The allowed result, once collected: setupId, setupToken, ingestKey, endpoint, task, ... */
165
+ this.setup = null;
166
+ /** The step being attempted once signed in, the `at` of a failure: signed-in, instrumented or running. */
167
+ this.step = null;
168
+ this.ended = false;
169
+ this.processes = new Set();
170
+ }
171
+
172
+ seconds(count) {
173
+ return count * this.ctx.second;
174
+ }
175
+
176
+ async run() {
177
+ const interrupt = () => {
178
+ this.interrupt();
179
+ };
180
+ this.ctx.signals?.on("SIGINT", interrupt);
181
+ try {
182
+ return await this.steps();
183
+ } catch (error) {
184
+ if (error instanceof Ended) return error.code;
185
+ const at = this.step ? ` at ${STEP_NAMES[this.step]}` : "";
186
+ this.say.error(`Failed${at}: ${error?.message ?? error}`);
187
+ if (this.setup && this.step && !this.ended) {
188
+ await this.end({ kind: "failed", at: this.step, reason: String(error?.message ?? error) });
189
+ }
190
+ return EXIT.failed;
191
+ } finally {
192
+ this.ctx.signals?.removeListener("SIGINT", interrupt);
193
+ for (const running of this.processes) running.stop();
194
+ this.say.close();
195
+ }
196
+ }
197
+
198
+ /** Ctrl-C: stop what the command started, report where it stopped, end with 1. A second Ctrl-C ends at once. */
199
+ async interrupt() {
200
+ if (this.interrupted) {
201
+ this.ctx.exit(EXIT.failed);
202
+ return;
203
+ }
204
+ this.interrupted = true;
205
+ for (const running of this.processes) running.stop();
206
+ this.say.error("");
207
+ this.say.error("Failed: stopped.");
208
+ if (this.setup && this.step && !this.ended) {
209
+ await this.end({ kind: "failed", at: this.step, reason: "stopped by the person running the setup" });
210
+ }
211
+ this.ctx.exit(EXIT.failed);
212
+ }
213
+
214
+ /** Say why it failed, report the end once signed in, and end with 1. */
215
+ async fail(message, reason, more = []) {
216
+ this.say.error(message);
217
+ for (const line of more) this.say.error(line);
218
+ if (this.setup && this.step && !this.ended) await this.end({ kind: "failed", at: this.step, reason: reason ?? message });
219
+ throw new Ended(EXIT.failed);
220
+ }
221
+
222
+ async report(step) {
223
+ try {
224
+ return (await this.service.report(this.setup.setupId, this.setup.setupToken, step)).ok;
225
+ } catch {
226
+ return false;
227
+ }
228
+ }
229
+
230
+ async end(end) {
231
+ this.ended = true;
232
+ const reported = end.reason === undefined ? end : { ...end, reason: clip(this.say.redact(end.reason)) };
233
+ await this.report({ step: "ended", end: reported });
234
+ }
235
+
236
+ async steps() {
237
+ const { folder } = this;
238
+ const { env } = this.ctx;
239
+ const name = folderName(folder);
240
+ const language = detectLanguage(folder);
241
+ const computer = computerName();
242
+ this.say.line(`impact.ai setup ${VERSION}`);
243
+ this.say.line(` Folder ${name} (${language === "other" ? "no Python or JavaScript manifest" : language})`);
244
+ this.say.line(` Computer ${computer}`);
245
+ this.say.line(` impact.ai ${this.options.origin}`);
246
+ this.say.line();
247
+
248
+ // Before anything: uncommitted work, a key already in .env, a coding agent. Stopping here changes nothing.
249
+ const repository = gitState(folder, env);
250
+ if (repository) {
251
+ const count = uncommittedFiles(folder, env);
252
+ if (count > 0) {
253
+ this.say.line(
254
+ `This folder's git repository has ${count} uncommitted ${count === 1 ? "file" : "files"}; ` +
255
+ "the coding agent's changes would mix with them.",
256
+ );
257
+ if (!(await this.say.confirm("Go on?"))) await this.fail("Failed: stopped. Nothing was changed.");
258
+ }
259
+ }
260
+ if (holdsKey(folder)) {
261
+ this.say.line(`This folder's .env already holds ${KEY}; the setup writes a new key in its place.`);
262
+ if (!(await this.say.confirm(`Replace ${KEY} in .env?`))) await this.fail("Failed: stopped. Nothing was changed.");
263
+ }
264
+ const found = findAgent(this.options.agent, env);
265
+ if (!found.agent) {
266
+ const missing = this.options.agent ? `${AGENTS[this.options.agent].name} is not installed` : "no coding agent is installed";
267
+ await this.fail(
268
+ `Failed: ${missing}. Install Claude Code, Codex or Cursor's CLI (now the Grok Build CLI, grok), ` +
269
+ "or name an installed one with --agent. Nothing was changed.",
270
+ undefined,
271
+ found.notes,
272
+ );
273
+ }
274
+ this.say.line(`Coding agent: ${found.agent.name}`);
275
+ this.say.line();
276
+
277
+ const allowed = await this.signIn({ computer, folder: name, language });
278
+ await this.signedIn(allowed, repository);
279
+ const reply = await this.instrument(found, Boolean(repository));
280
+ return this.runOnce(reply, name);
281
+ }
282
+
283
+ /** Start a setup, open its allow page, and collect the result once a person allows it. */
284
+ async signIn(body) {
285
+ let started;
286
+ try {
287
+ started = await this.service.start(body);
288
+ } catch (error) {
289
+ await this.fail(`Failed: impact.ai cannot be reached at ${this.options.origin} (${error.message}). Nothing was changed.`);
290
+ }
291
+ if (!started.ok) {
292
+ const why =
293
+ started.status === 429
294
+ ? "too many setups were started from this address; try again in a few minutes"
295
+ : `impact.ai answered ${started.status}`;
296
+ await this.fail(`Failed: the setup could not start: ${why}. Nothing was changed.`);
297
+ }
298
+ const setup = started.body ?? {};
299
+ if (typeof setup.deviceCode !== "string" || !setup.deviceCode || typeof setup.allowUrl !== "string") {
300
+ await this.fail("Failed: impact.ai's answer held no device code or allow address. Nothing was changed.");
301
+ }
302
+ this.say.secret(setup.deviceCode);
303
+ if (!sameOrigin(setup.allowUrl, this.options.origin)) {
304
+ await this.fail(`Failed: impact.ai's allow address is not on ${this.options.origin}, so it was not opened. Nothing was changed.`);
305
+ }
306
+ let interval = Number.isFinite(setup.interval) && setup.interval >= 0 ? setup.interval : 5;
307
+ const opened = openBrowser(setup.allowUrl, this.ctx.env);
308
+ this.say.line(opened ? "Allow the setup in the browser, or open this address:" : "Open this address in a browser to allow the setup:");
309
+ this.say.line(` ${setup.allowUrl}`);
310
+ if (typeof setup.userCode === "string") this.say.line(` Its code is ${setup.userCode}.`);
311
+ this.say.line("An Owner or Admin of the Workspace allows it. Waiting up to 10 minutes...");
312
+
313
+ const deadline = Date.now() + this.seconds(ALLOW_WINDOW);
314
+ let unreachable = false;
315
+ for (;;) {
316
+ const remaining = deadline - Date.now();
317
+ if (remaining <= 0) break;
318
+ await sleep(Math.min(this.seconds(interval), remaining));
319
+ let answer;
320
+ try {
321
+ answer = await this.service.collect(setup.deviceCode);
322
+ } catch (error) {
323
+ if (!unreachable) this.say.line(`impact.ai cannot be reached (${error.message}); trying again.`);
324
+ unreachable = true;
325
+ continue;
326
+ }
327
+ unreachable = false;
328
+ if (answer.status === 429) {
329
+ interval += SLOW_DOWN;
330
+ continue;
331
+ }
332
+ if (answer.status >= 500) continue;
333
+ if (!answer.ok) await this.fail(`Failed: not allowed (impact.ai answered ${answer.status}). Nothing was changed.`);
334
+ const status = answer.body?.status;
335
+ if (status === "slow_down") interval += SLOW_DOWN;
336
+ else if (status === "denied") await this.fail("Failed: not allowed. The setup was denied. Nothing was changed.");
337
+ else if (status === "expired") {
338
+ await this.fail("Failed: not allowed. The setup expired before anyone allowed it. Nothing was changed.");
339
+ } else if (status === "collected") {
340
+ await this.fail(
341
+ "Failed: not allowed. This setup's result was already collected, and impact.ai hands it out only once: " +
342
+ "run the command again. Nothing was changed.",
343
+ );
344
+ } else if (status === "allowed") return answer.body;
345
+ // pending, or a status this version does not know: ask again after the interval
346
+ }
347
+ return this.fail("Failed: not allowed. Nobody allowed the setup within 10 minutes. Nothing was changed.");
348
+ }
349
+
350
+ /** Hold the result, say what was allowed, and write the key to .env (and .env to .gitignore). */
351
+ async signedIn(allowed, repository) {
352
+ for (const secret of [allowed.ingestKey, allowed.setupToken]) this.say.secret(secret);
353
+ if (typeof allowed.setupId === "string" && typeof allowed.setupToken === "string" && allowed.setupToken) {
354
+ this.setup = allowed;
355
+ }
356
+ this.step = "signed-in";
357
+ const missing = ["setupId", "setupToken", "ingestKey", "endpoint", "task"].filter(
358
+ (field) => typeof allowed[field] !== "string" || !allowed[field],
359
+ );
360
+ if (missing.length) {
361
+ await this.fail(`Failed at Signed in: impact.ai's answer held no ${missing.join(", ")}.`, `the answer held no ${missing.join(", ")}`);
362
+ }
363
+ if (!isAddress(allowed.endpoint)) {
364
+ await this.fail("Failed at Signed in: the ingest address impact.ai gave is not an https address.", "the ingest address is not https");
365
+ }
366
+ if ([allowed.ingestKey, allowed.setupToken].some((secret) => allowed.task.includes(secret))) {
367
+ await this.fail(
368
+ "Failed at Signed in: impact.ai's task for the coding agent held a secret, so it was not handed over.",
369
+ "the agent's task held a secret",
370
+ );
371
+ }
372
+ this.say.line("Signed in.");
373
+ this.say.line(` Workspace ${allowed.workspace?.name ?? "-"}`);
374
+ this.say.line(` Product ${allowed.product?.name ?? "-"}`);
375
+ this.say.line(` Key ${allowed.keyName ?? "-"}`);
376
+ const content = contentLine(allowed.product);
377
+ if (content) this.say.line(` ${content}`);
378
+ try {
379
+ const ignored = ensureIgnored(this.folder, repository ? gitIgnores(this.folder, this.ctx.env, ".env") : null);
380
+ writeEnv(this.folder, { [KEY]: allowed.ingestKey, [ENDPOINT]: allowed.endpoint });
381
+ const note = { created: "; created .gitignore with .env", added: "; added .env to .gitignore", ignored: "" }[ignored];
382
+ this.say.line(` Wrote ${KEY} and ${ENDPOINT} to .env${note}.`);
383
+ } catch (error) {
384
+ const why = error.code || error.message;
385
+ await this.fail(`Failed at Signed in: could not write .env (${why}).`, `could not write .env (${why})`);
386
+ }
387
+ this.say.line();
388
+ }
389
+
390
+ /** Hand the task to the coding agent and read its reply; it must not commit. */
391
+ async instrument({ agent, path: program }, inRepository) {
392
+ this.step = "instrumented";
393
+ const { args, input } = invocation(agent, composePrompt(this.setup.task), { inRepository });
394
+ const before = gitState(this.folder, this.ctx.env);
395
+ this.say.line(`${agent.name} is adding the instrumentation. This can take a few minutes.`);
396
+ const running = start(program, args, {
397
+ cwd: this.folder,
398
+ env: withoutKeys(this.ctx.env),
399
+ input,
400
+ onLine: (line) => this.say.quote(line),
401
+ });
402
+ this.processes.add(running);
403
+ const result = await running.exited;
404
+ this.processes.delete(running);
405
+ if (result.error) {
406
+ await this.fail(`Failed at Instrumented: ${agent.name} could not start (${result.error}).`, `${agent.name} could not start (${result.error})`);
407
+ }
408
+ if (result.code !== 0) {
409
+ const exit = result.code === null ? `was stopped (${result.signal})` : `exited with code ${result.code}`;
410
+ await this.fail(
411
+ `Failed at Instrumented: ${agent.name} ${exit}. The working tree stays as it left it.`,
412
+ `${agent.name} ${exit}`,
413
+ );
414
+ }
415
+ const after = gitState(this.folder, this.ctx.env);
416
+ if (headMoved(before, after)) {
417
+ await this.fail(
418
+ `Failed at Instrumented: ${agent.name} committed (HEAD moved from ${before.head?.slice(0, 12) ?? "no commit"} to ` +
419
+ `${after.head?.slice(0, 12) ?? "no commit"}), and the setup lets no coding agent commit. Review what it ` +
420
+ "committed with git log -p before you push anything.",
421
+ `${agent.name} committed: HEAD moved`,
422
+ );
423
+ }
424
+ const reply = parseReply(result.stdout);
425
+ if (reply.unsupported.length) {
426
+ const names = reply.unsupported.join(", ");
427
+ await this.fail(
428
+ `Failed at Instrumented: ${agent.name} could not cover ${names}. Nothing more was changed, and the working ` +
429
+ "tree stays as the agent left it.",
430
+ `${agent.name} could not cover: ${names}`,
431
+ [
432
+ "To send its traces anyway, set an OpenTelemetry exporter by hand, from the two variables in .env:",
433
+ ` OTEL_EXPORTER_OTLP_TRACES_ENDPOINT the value of ${ENDPOINT}`,
434
+ ` OTEL_EXPORTER_OTLP_TRACES_HEADERS authorization=Bearer%20<the value of ${KEY}>`,
435
+ ],
436
+ );
437
+ }
438
+ await this.report({ step: "instrumented" });
439
+ this.say.line(`Instrumented by ${agent.name}.`);
440
+ return reply;
441
+ }
442
+
443
+ /** Run the application once, after the person confirms, and wait for its trace to be received and checked. */
444
+ async runOnce(reply, folder) {
445
+ this.step = "running";
446
+ const service = reply.service ?? folder;
447
+ const environment = reply.environment ?? this.setup.environment ?? "development";
448
+ let command = reply.run;
449
+ if (!command) {
450
+ this.say.line("The coding agent named no command that runs the application.");
451
+ command = await this.say.ask("Which command runs it once, from this folder? (empty to stop)");
452
+ if (!command) {
453
+ await this.fail(
454
+ `Failed at Running: no command to run the application. Run it yourself with ${KEY} and ${ENDPOINT} from .env ` +
455
+ "to send its first trace.",
456
+ "no command to run the application",
457
+ );
458
+ }
459
+ }
460
+ this.say.line(` Service ${service}${reply.service ? "" : " (the folder's name: the agent named none)"}`);
461
+ this.say.line(` Run ${command}`);
462
+ if (!(await this.say.confirm(`Run it once now, with ${KEY} and ${ENDPOINT} from .env?`, { defaultYes: true }))) {
463
+ await this.fail(
464
+ "Failed: stopped before the run. The instrumentation and .env stay; run the application to send its first trace.",
465
+ "stopped before the run",
466
+ );
467
+ }
468
+ const values = readEnvValues(this.folder, [KEY, ENDPOINT]);
469
+ // The wait counts from here, as impact.ai's does: the coding agent's time never shortens it.
470
+ const runningAt = Date.now();
471
+ await this.report({ step: "running", service, environment, command });
472
+ this.say.line(`Running ${service} in ${environment}: ${command}`);
473
+ const app = start(command, [], {
474
+ cwd: this.folder,
475
+ env: { ...this.ctx.env, [KEY]: values[KEY] ?? this.setup.ingestKey, [ENDPOINT]: values[ENDPOINT] ?? this.setup.endpoint },
476
+ shell: true,
477
+ settleOn: "exit",
478
+ onLine: (line) => this.say.quote(line),
479
+ });
480
+ this.processes.add(app);
481
+ return this.waitForTrace(app, command, runningAt);
482
+ }
483
+
484
+ async waitForTrace(app, command, runningAt) {
485
+ const deadline = runningAt + this.seconds(TRACE_WINDOW);
486
+ let runEnd = null;
487
+ app.exited.then((result) => {
488
+ runEnd = { ...result, at: Date.now() };
489
+ });
490
+ let received = null;
491
+ let unreachable = false;
492
+ let stopped = null;
493
+ this.say.line(`Waiting for its first trace, until ${clock(deadline)}.`);
494
+ for (;;) {
495
+ let status = null;
496
+ try {
497
+ const answer = await this.service.status(this.setup.setupId, this.setup.setupToken);
498
+ if (unreachable) this.say.line("impact.ai can be reached again.");
499
+ unreachable = false;
500
+ if (answer.status === 401) {
501
+ stopped = "impact.ai no longer accepts this setup's token: the setup ended or expired.";
502
+ break;
503
+ }
504
+ if (answer.ok) status = answer.body;
505
+ } catch (error) {
506
+ if (!unreachable) this.say.line(`impact.ai cannot be reached (${error.message}); trying again until ${clock(deadline)}.`);
507
+ unreachable = true;
508
+ }
509
+ const steps = status?.steps ?? {};
510
+ if (steps.traceReceived && !received) {
511
+ received = steps.traceReceived;
512
+ this.say.line(describeTrace(received));
513
+ }
514
+ if (steps.checked) {
515
+ this.say.line(describeChecked(steps.checked));
516
+ if (typeof status.traceUrl === "string") this.say.line(` ${status.traceUrl}`);
517
+ if (!runEnd) this.say.line("Stopping the application the setup started.");
518
+ return EXIT.checked;
519
+ }
520
+ if (status?.keyRevoked) {
521
+ stopped = "The setup's key was revoked in impact.ai.";
522
+ break;
523
+ }
524
+ if (status?.end) {
525
+ stopped = "impact.ai ended this setup.";
526
+ break;
527
+ }
528
+ if (runEnd && runEnd.code !== 0 && !received && Date.now() - runEnd.at >= this.seconds(RUN_GRACE)) {
529
+ const exit = runEnd.error
530
+ ? `could not start (${runEnd.error})`
531
+ : runEnd.code === null
532
+ ? `was stopped (${runEnd.signal})`
533
+ : `exited with code ${runEnd.code}`;
534
+ await this.fail(`Failed at Running: ${command} ${exit}, and no trace arrived.`, `the run ${exit}`);
535
+ }
536
+ const remaining = deadline - Date.now();
537
+ if (remaining <= 0) break;
538
+ await sleep(Math.min(this.seconds(STATUS_EVERY), remaining));
539
+ }
540
+ app.stop();
541
+ const follow = typeof this.setup.progressUrl === "string" ? `Follow this setup at ${this.setup.progressUrl}` : null;
542
+ if (received) {
543
+ this.say.line(`The trace that arrived at ${clock(received.at)} was not checked in time.${stopped ? ` ${stopped}` : ""}`);
544
+ if (!stopped) await this.end({ kind: "unchecked" });
545
+ } else if (stopped) {
546
+ this.say.line(stopped);
547
+ } else {
548
+ this.say.line(
549
+ unreachable
550
+ ? "No trace has arrived in 15 minutes: impact.ai could not be reached until the wait ended."
551
+ : "No trace has arrived in 15 minutes.",
552
+ );
553
+ this.say.line("Check that:");
554
+ this.say.line(` - the application reads ${KEY} and ${ENDPOINT} (from .env or its environment) when it starts;`);
555
+ this.say.line(` - it can reach ${new URL(this.setup.endpoint).origin} from this computer;`);
556
+ this.say.line(" - the run makes at least one model call.");
557
+ await this.end({ kind: "no-trace" });
558
+ }
559
+ if (follow) this.say.line(follow);
560
+ return EXIT.unchecked;
561
+ }
562
+ }