intent-prompt-graph 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 umiddey
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,158 @@
1
- # Temporary Holding Version
1
+ # intent-prompt-graph
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A local tool that turns a coding-agent session into a live **Decision & Path Graph** (DAG): what goal started the session, what options were proposed, what paths were rejected and why, what repetitive loops happened, and what path was chosen. It runs a loopback-only daemon and serves the dark-mode graph in the browser.
4
+
5
+ Without a `labeler` you get a basic outline, not the real decision graph: node titles are raw message text, and a long session shows only its latest steps (older ones are collapsed into one node). No API key is needed for that. Configure a `labeler` (see [Config](#config)) to get the real decision graph, extracted by an LLM.
6
+
7
+ ## What it is
8
+
9
+ Three parts in one npm package:
10
+
11
+ - `ipg`: a standalone CLI and local daemon (needs [Bun](https://bun.sh)). Works from any shell. It reads sessions of two harnesses: OMP (`--harness omp`, the default) and Claude Code (`--harness claude`).
12
+ - An OMP plugin that adds the `/ipg` slash command (a thin wrapper around `ipg open`).
13
+ - Claude Code slash commands that do the same there (see [Claude Code](#claude-code)).
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ bun add -g intent-prompt-graph # puts `ipg` on PATH
19
+ omp plugin install intent-prompt-graph # adds /ipg to OMP
20
+ ```
21
+
22
+ From a checkout instead:
23
+
24
+ ```sh
25
+ bun install
26
+ bun link # `ipg` on PATH
27
+ omp plugin link "$PWD" # /ipg in OMP
28
+ ```
29
+
30
+ ## OMP integration
31
+
32
+ `/ipg` runs `ipg open --harness omp --session-file <file>` for the current
33
+ session and prints the URL. It calls the `ipg` CLI on PATH and does not import
34
+ daemon code. A session that is not saved to disk gets a warning instead of a
35
+ graph. The plugin entry is the `omp.extensions` field of `package.json`
36
+ (`integrations/omp/intent-graph.ts`).
37
+
38
+ ## Claude Code
39
+
40
+ `ipg` reads Claude Code sessions with `--harness claude`:
41
+
42
+ ```sh
43
+ ipg open --harness claude # the session of this terminal or directory
44
+ ipg log --harness claude --session-file ~/.claude/projects/<project>/<session id>.jsonl
45
+ ```
46
+
47
+ Without `--session-file` it finds the session in two steps:
48
+
49
+ 1. It walks up its own parent processes. A running Claude Code process records
50
+ its session id in `~/.claude/sessions/<pid>.json`, so when `ipg` is started
51
+ from inside Claude Code (a slash command or the Bash tool) it gets exactly
52
+ that session.
53
+ 2. Otherwise it takes the newest session of the current directory under
54
+ `~/.claude/projects/`.
55
+
56
+ `CLAUDE_CONFIG_DIR` replaces `~/.claude` when it is set, as in Claude Code.
57
+
58
+ A message becomes an owner turn only when the owner wrote it. Tool output,
59
+ slash-command and `!` shell wrappers, system reminders, task notifications,
60
+ compaction summaries and subagent conversations do not.
61
+
62
+ The slash commands are the files `integrations/claude/commands/*.md` of this
63
+ package. Copy or link them into your Claude Code commands directory (or into
64
+ `.claude/commands/` of one project). From a checkout:
65
+
66
+ ```sh
67
+ mkdir -p ~/.claude/commands
68
+ ln -s "$PWD"/integrations/claude/commands/*.md ~/.claude/commands/
69
+ ```
70
+
71
+ - `/ipg` runs `ipg open --harness claude` and replies with the URL.
72
+ - `/ipg-log` writes the decision log to `/tmp/ipg-log-<session id>.md` and
73
+ replies with the path.
74
+ - `/ipg-rejected` puts the rejected paths into the conversation, so the agent
75
+ does not propose them again. When nothing was rejected it says so.
76
+
77
+ Each command runs `ipg` before the model sees the prompt and then costs one
78
+ short model reply. A brand-new session has no file on disk until its first
79
+ message is sent, so the commands report an error when they are the very first
80
+ thing typed.
81
+
82
+ ## Decision log
83
+
84
+ `ipg log` prints the record under the graph as markdown: the goal, what was
85
+ chosen, what was rejected and why, the decisions and the loops.
86
+
87
+ ```sh
88
+ ipg log [--harness omp|claude] [--session-file <file.jsonl>] [--rejected] [--out <file.md>]
89
+ ```
90
+
91
+ - It reads the graph the labeler already stored for the session. When there is
92
+ none it builds the basic outline from the session file. The last line of the
93
+ log says which one you got. It does not start the daemon and calls no model.
94
+ - Without `--session-file` it finds the session of the current terminal, as
95
+ `ipg open` does.
96
+ - `--out` writes the log to a file instead of printing it.
97
+ - `--rejected` prints only the rejected paths, as a short block to paste into
98
+ an agent prompt so the agent does not propose them again. Options that were
99
+ laid out but never rejected are left out of this block. It prints nothing
100
+ when nothing was rejected.
101
+
102
+ In OMP:
103
+
104
+ - `/ipg-log` writes the log to `ipg-log-<session id>.md` in the system temp
105
+ directory and shows the path. Hand that file to a new session instead of the
106
+ old conversation.
107
+ - `/ipg-rejected` pastes the rejected block into the input editor. You review
108
+ it and send it yourself. When nothing was rejected it says so.
109
+
110
+ In Claude Code the same two commands exist; see [Claude Code](#claude-code).
111
+
112
+ ## Config
113
+
114
+ Optional file: `$XDG_CONFIG_HOME/intent-prompt-graph/config.json`, or
115
+ `~/.config/intent-prompt-graph/config.json` when `XDG_CONFIG_HOME` is unset. A
116
+ missing file means defaults.
117
+
118
+ ```json
119
+ {
120
+ "port": 4761,
121
+ "idleExitMinutes": 15,
122
+ "harnessText": ["^<system-reminder"],
123
+ "labeler": {
124
+ "baseUrl": "https://api.example.com/v1",
125
+ "model": "example-model",
126
+ "apiKeyEnv": "IPG_LABELER_KEY"
127
+ }
128
+ }
129
+ ```
130
+
131
+ - `port`: loopback port of the daemon (default 4761).
132
+ - `idleExitMinutes`: the daemon exits after this many minutes with no open browser tab (default 15).
133
+ - `harnessText`: regular expressions. Matching text is treated as harness-injected, not owner-authored.
134
+ - `labeler`: the model that extracts the decision graph. Without it you only get the basic outline. Two providers:
135
+ - `"provider": "openai"` (the default when `provider` is omitted): any OpenAI-compatible endpoint. Fields: `baseUrl`, `model`, and optionally `apiKeyEnv`, which names an environment variable that holds the key. The key itself never goes in the config file.
136
+ - `"provider": "claude-cli"`: runs the local Claude Code CLI instead of calling an HTTP endpoint. Fields: `provider`, `model`, and optionally `command` (binary name or path, default `claude`). `baseUrl` and `apiKeyEnv` are not used.
137
+
138
+ ```json
139
+ {
140
+ "labeler": {
141
+ "provider": "claude-cli",
142
+ "model": "haiku",
143
+ "command": "claude"
144
+ }
145
+ }
146
+ ```
147
+
148
+ ## Labeler and privacy
149
+
150
+ The labeler sends the conversation to the endpoint you configure, or to the local `claude` command when the provider is `claude-cli`. It sends:
151
+
152
+ - owner messages, truncated to 800 characters;
153
+ - agent messages, truncated to 1200 characters;
154
+ - tool use as counts per tool name, not tool output;
155
+ - guest messages replaced by the placeholder `[guest message withheld]`;
156
+ - after the first batch, an outline of the graph so far (node ids, kinds and titles, edge endpoints and kinds), so the model replies with only what changed.
157
+
158
+ Choose an endpoint or CLI account you trust with those contents. Nothing is sent anywhere else.
@@ -0,0 +1,10 @@
1
+ ---
2
+ description: Write the decision log of this session to a markdown file
3
+ allowed-tools: Bash(ipg log:*)
4
+ ---
5
+
6
+ !`ipg log --harness claude --out /tmp/ipg-log-${CLAUDE_SESSION_ID}.md`
7
+
8
+ The decision log of this session was written to `/tmp/ipg-log-${CLAUDE_SESSION_ID}.md`.
9
+
10
+ Reply with only that path, on a line of its own. If an error is printed above instead, show the error as it is.
@@ -0,0 +1,10 @@
1
+ ---
2
+ description: List the paths rejected in this session so they are not proposed again
3
+ allowed-tools: Bash(ipg log:*)
4
+ ---
5
+
6
+ Paths rejected earlier in this session:
7
+
8
+ !`ipg log --harness claude --rejected`
9
+
10
+ Show the block above to the user as it is. Treat every path listed in it as already rejected: do not propose it again in this session. If no rejected paths are listed above, reply with only "Nothing rejected yet". If an error is printed above instead, show the error as it is.
@@ -0,0 +1,10 @@
1
+ ---
2
+ description: Open the decision graph of this session in the browser
3
+ allowed-tools: Bash(ipg open:*)
4
+ ---
5
+
6
+ Output of `ipg open` for this session:
7
+
8
+ !`ipg open --harness claude`
9
+
10
+ Reply with only the URL from that output, on a line of its own. If the output is an error instead of a URL, show the error as it is.
@@ -0,0 +1,65 @@
1
+ import { execFile } from "node:child_process";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import type { ExtensionAPI, ExtensionCommandContext } from "./types";
5
+
6
+ // Type-only import: Bun erases it, so the file loads with no runtime dependency on types.d.ts.
7
+ // The extension shells out to the `ipg` CLI on PATH instead of importing the daemon code.
8
+
9
+ /** Runs `ipg <command> --harness omp --session-file <file> …extra` and resolves with its stdout. */
10
+ function runIpg(command: string, sessionFile: string, extra: string[] = []): Promise<string> {
11
+ const { promise, resolve, reject } = Promise.withResolvers<string>();
12
+ execFile("ipg", [command, "--harness", "omp", "--session-file", sessionFile, ...extra], (err, stdout, stderr) => {
13
+ if (err) reject(new Error(stderr.trim() || err.message));
14
+ else resolve(stdout);
15
+ });
16
+ return promise;
17
+ }
18
+
19
+ /**
20
+ * Wraps a command body with the handling every command shares: a warning when the session is
21
+ * not saved to disk, and an error notification when the `ipg` call fails.
22
+ */
23
+ function command(
24
+ label: string,
25
+ body: (sessionFile: string, ctx: ExtensionCommandContext) => Promise<void>,
26
+ ): (args: string, ctx: ExtensionCommandContext) => Promise<void> {
27
+ return async (_args, ctx) => {
28
+ const sessionFile = ctx.sessionManager.getSessionFile();
29
+ if (sessionFile === undefined) {
30
+ ctx.ui.notify("This session is not saved to disk", "warning");
31
+ return;
32
+ }
33
+ try {
34
+ await body(sessionFile, ctx);
35
+ } catch (err) {
36
+ ctx.ui.notify(`${label} failed: ${err instanceof Error ? err.message : String(err)}`, "error");
37
+ }
38
+ };
39
+ }
40
+
41
+ export default function (pi: ExtensionAPI): void {
42
+ pi.registerCommand("ipg", {
43
+ description: "Open the intent graph of this session in the browser",
44
+ handler: command("ipg open", async (sessionFile, ctx) => {
45
+ const lines = (await runIpg("open", sessionFile)).trim().split("\n");
46
+ ctx.ui.notify(lines[lines.length - 1] ?? "", "info");
47
+ }),
48
+ });
49
+ pi.registerCommand("ipg-log", {
50
+ description: "Write the decision log of this session to a markdown file",
51
+ handler: command("ipg log", async (sessionFile, ctx) => {
52
+ const out = join(tmpdir(), `ipg-log-${ctx.sessionManager.getSessionId()}.md`);
53
+ await runIpg("log", sessionFile, ["--out", out]);
54
+ ctx.ui.notify(out, "info");
55
+ }),
56
+ });
57
+ pi.registerCommand("ipg-rejected", {
58
+ description: "Paste the paths rejected in this session into the editor",
59
+ handler: command("ipg log", async (sessionFile, ctx) => {
60
+ const block = (await runIpg("log", sessionFile, ["--rejected"])).trim();
61
+ if (block) ctx.ui.pasteToEditor(block);
62
+ else ctx.ui.notify("Nothing rejected yet", "info");
63
+ }),
64
+ });
65
+ }
@@ -0,0 +1,30 @@
1
+ // Minimal structural subset of the OMP extension API (pi-coding-agent
2
+ // src/extensibility/extensions/types.ts). Only the members intent-graph.ts uses
3
+ // are declared; the real runtime objects are richer.
4
+
5
+ export interface ExtensionUIContext {
6
+ notify(message: string, type?: "info" | "warning" | "error"): void;
7
+ /** Pastes text into the input editor; the owner still has to send it. */
8
+ pasteToEditor(text: string): void;
9
+ }
10
+
11
+ export interface ReadonlySessionManager {
12
+ getSessionId(): string;
13
+ getSessionFile(): string | undefined;
14
+ }
15
+
16
+ export interface ExtensionCommandContext {
17
+ ui: ExtensionUIContext;
18
+ sessionManager: ReadonlySessionManager;
19
+ }
20
+
21
+ export interface RegisteredCommandOptions {
22
+ description?: string;
23
+ handler: (args: string, ctx: ExtensionCommandContext) => Promise<void>;
24
+ }
25
+
26
+ export interface ExtensionAPI {
27
+ registerCommand(name: string, options: RegisteredCommandOptions): void;
28
+ }
29
+
30
+ export type ExtensionFactory = (pi: ExtensionAPI) => void | Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "intent-prompt-graph",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "A live browser graph of a coding-agent conversation, grouped by intent. Standalone `ipg` CLI plus plugins for OMP and Claude Code that add /ipg.",
5
+ "keywords": [
6
+ "ai-agents",
7
+ "coding-agents",
8
+ "omp",
9
+ "bun",
10
+ "cli",
11
+ "graph"
12
+ ],
13
+ "homepage": "https://github.com/umiddey/intent-prompt-graph#readme",
14
+ "bugs": "https://github.com/umiddey/intent-prompt-graph/issues",
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/umiddey/intent-prompt-graph.git"
19
+ },
20
+ "engines": {
21
+ "bun": ">=1.0"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "files": [
27
+ "src",
28
+ "web",
29
+ "integrations",
30
+ "README.md",
31
+ "LICENSE"
32
+ ],
33
+ "bin": {
34
+ "ipg": "src/cli.ts"
35
+ },
36
+ "omp": {
37
+ "extensions": [
38
+ "./integrations/omp/intent-graph.ts"
39
+ ]
40
+ },
41
+ "scripts": {
42
+ "test": "bun test",
43
+ "typecheck": "tsc --noEmit"
44
+ },
45
+ "devDependencies": {
46
+ "@types/bun": "^1.4.5",
47
+ "typescript": "^7.0.2"
48
+ }
49
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,212 @@
1
+ #!/usr/bin/env bun
2
+ import { writeFileSync } from "node:fs";
3
+ import { configFile, type Config, loadConfig } from "./config";
4
+ import { renderDecisionLog } from "./export";
5
+ import { type Harness, harnessById, type SessionRef } from "./harness/harness";
6
+ import { buildHeuristicGraph } from "./heuristic";
7
+ import type { Turn } from "./model";
8
+ import { APP, startDaemon } from "./server";
9
+ import { openStore } from "./store";
10
+ import { tailJsonl } from "./tail";
11
+
12
+ const USAGE = [
13
+ "usage: ipg turns --harness omp|claude --session-file <file.jsonl>",
14
+ " ipg serve [--port N]",
15
+ " ipg open [--harness omp|claude] [--session-file <file.jsonl>] [--no-browser] [--port N]",
16
+ " ipg log [--harness omp|claude] [--session-file <file.jsonl>] [--rejected] [--out <file.md>]",
17
+ ].join("\n");
18
+
19
+ // The reader closed the pipe (e.g. `| head`): exit quietly, as other Unix tools do.
20
+ process.stdout.on("error", (err: NodeJS.ErrnoException) => {
21
+ if (err.code === "EPIPE") process.exit(0);
22
+ console.error(`ipg: ${err.message}`);
23
+ process.exit(1);
24
+ });
25
+
26
+ function flag(args: string[], name: string): string | undefined {
27
+ const i = args.indexOf(name);
28
+ return i === -1 ? undefined : args[i + 1];
29
+ }
30
+
31
+ function parsePort(value: string): number {
32
+ const n = Number(value);
33
+ if (!Number.isInteger(n) || n < 1 || n > 65535) throw new Error(`--port must be an integer from 1 to 65535`);
34
+ return n;
35
+ }
36
+
37
+ function portOf(args: string[], config: Config): number {
38
+ const value = flag(args, "--port");
39
+ return value === undefined ? config.port : parsePort(value);
40
+ }
41
+
42
+ /** Reads the whole session file once and returns its turns in first-appearance order. */
43
+ async function readTurns(harness: Harness, ref: SessionRef, config: Config): Promise<Turn[]> {
44
+ let reader = harness.reader(ref, { config });
45
+ const byId = new Map<string, Turn>();
46
+ await tailJsonl(
47
+ ref.file,
48
+ (ev) => {
49
+ if (ev.type === "reset") {
50
+ reader = harness.reader(ref, { config });
51
+ byId.clear();
52
+ return;
53
+ }
54
+ for (const t of reader.push(ev.record)) byId.set(t.id, t);
55
+ },
56
+ { follow: false },
57
+ );
58
+ return [...byId.values()];
59
+ }
60
+
61
+ /** Finds the session from --session-file, else the way the harness finds its running session. */
62
+ async function locateSession(harness: Harness, args: string[]): Promise<SessionRef> {
63
+ return harness.locate({
64
+ sessionFile: flag(args, "--session-file"),
65
+ tty: await ttyName(),
66
+ cwd: process.cwd(),
67
+ });
68
+ }
69
+
70
+ /** Prints the final turn list, one JSON object per line, in first-appearance order. */
71
+ async function turns(args: string[]): Promise<number> {
72
+ const harness = harnessById(flag(args, "--harness") ?? "");
73
+ const sessionFile = flag(args, "--session-file");
74
+ if (!harness || !sessionFile) {
75
+ console.error(USAGE);
76
+ return 2;
77
+ }
78
+ const ref = await harness.locate({ sessionFile, cwd: process.cwd() });
79
+ for (const t of await readTurns(harness, ref, loadConfig())) process.stdout.write(`${JSON.stringify(t)}\n`);
80
+ return 0;
81
+ }
82
+
83
+ /**
84
+ * Prints the decision log of a session as markdown, or writes it to --out.
85
+ * Reads the stored LLM graph when there is one, else builds the heuristic outline from the
86
+ * session file. Never starts the daemon and never calls the labeler.
87
+ */
88
+ async function log(args: string[]): Promise<number> {
89
+ const harness = harnessById(flag(args, "--harness") ?? "omp");
90
+ const out = flag(args, "--out");
91
+ if (!harness || (args.includes("--out") && !out)) {
92
+ console.error(USAGE);
93
+ return 2;
94
+ }
95
+ const ref = await locateSession(harness, args);
96
+ const stored = openStore(harness.id, ref.key).graph;
97
+ const graph =
98
+ stored && stored.nodes.length > 0
99
+ ? stored
100
+ : buildHeuristicGraph(await readTurns(harness, ref, loadConfig()), ref.title);
101
+ const text = renderDecisionLog(graph, args.includes("--rejected") ? { only: "rejected" } : undefined);
102
+ if (out) writeFileSync(out, text);
103
+ else process.stdout.write(text);
104
+ return 0;
105
+ }
106
+
107
+ /** Runs the daemon in the foreground; it exits on its own after the idle window. */
108
+ async function serve(args: string[]): Promise<number> {
109
+ const config = loadConfig();
110
+ startDaemon({ config, port: portOf(args, config), onIdle: () => process.exit(0) });
111
+ return 0;
112
+ }
113
+
114
+ /** Ensures a daemon is answering, then prints the session URL. */
115
+ async function open(args: string[]): Promise<number> {
116
+ const harness = harnessById(flag(args, "--harness") ?? "omp");
117
+ if (!harness) {
118
+ console.error(USAGE);
119
+ return 2;
120
+ }
121
+ const config = loadConfig();
122
+ const port = portOf(args, config);
123
+ const ref = await locateSession(harness, args);
124
+ await ensureDaemon(port);
125
+ const url = `http://127.0.0.1:${port}/s/${harness.id}/${ref.key}#latest`;
126
+ console.log(url);
127
+ if (!args.includes("--no-browser")) openBrowser(url);
128
+ return 0;
129
+ }
130
+
131
+ /** The terminal this process runs in, or undefined when stdin is not a tty. */
132
+ async function ttyName(): Promise<string | undefined> {
133
+ try {
134
+ const proc = Bun.spawn(["tty"], { stdin: "inherit", stdout: "pipe", stderr: "ignore" });
135
+ const out = (await new Response(proc.stdout).text()).trim();
136
+ return (await proc.exited) === 0 ? out : undefined;
137
+ } catch {
138
+ return undefined;
139
+ }
140
+ }
141
+
142
+ type Health = "ours" | "foreign" | "none";
143
+
144
+ async function health(port: number): Promise<Health> {
145
+ let res: Response;
146
+ try {
147
+ res = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(500) });
148
+ } catch {
149
+ return "none";
150
+ }
151
+ const body: unknown = await res.json().catch(() => undefined);
152
+ const ours = res.ok && typeof body === "object" && body !== null && "app" in body && body.app === APP;
153
+ return ours ? "ours" : "foreign";
154
+ }
155
+
156
+ function foreignPortError(port: number): Error {
157
+ return new Error(`port ${port} is used by another program; set "port" in ${configFile()} or pass --port`);
158
+ }
159
+
160
+ /** Starts a detached daemon when nothing answers on the port; refuses a foreign listener. */
161
+ async function ensureDaemon(port: number): Promise<void> {
162
+ const first = await health(port);
163
+ if (first === "ours") return;
164
+ if (first === "foreign") throw foreignPortError(port);
165
+ Bun.spawn([process.execPath, import.meta.path, "serve", "--port", String(port)], {
166
+ stdio: ["ignore", "ignore", "ignore"],
167
+ }).unref();
168
+ await awaitDaemon(port, Date.now() + 3000);
169
+ }
170
+
171
+ /** Polls /health every 100 ms until the daemon answers or the deadline passes. */
172
+ async function awaitDaemon(port: number, deadline: number): Promise<void> {
173
+ await Bun.sleep(100);
174
+ const state = await health(port);
175
+ if (state === "ours") return;
176
+ if (state === "foreign") throw foreignPortError(port);
177
+ if (Date.now() >= deadline) throw new Error(`daemon did not answer on port ${port} within 3 s`);
178
+ return awaitDaemon(port, deadline);
179
+ }
180
+
181
+ function openBrowser(url: string): void {
182
+ const opener = process.platform === "darwin" ? "open" : "xdg-open";
183
+ try {
184
+ Bun.spawn([opener, url], { stdio: ["ignore", "ignore", "ignore"] }).unref();
185
+ } catch {
186
+ console.error(`ipg: could not run ${opener}; open the URL above`);
187
+ }
188
+ }
189
+
190
+ async function main(argv: string[]): Promise<number> {
191
+ const [cmd, ...rest] = argv;
192
+ try {
193
+ switch (cmd) {
194
+ case "turns":
195
+ return await turns(rest);
196
+ case "serve":
197
+ return await serve(rest);
198
+ case "open":
199
+ return await open(rest);
200
+ case "log":
201
+ return await log(rest);
202
+ default:
203
+ console.error(USAGE);
204
+ return 2;
205
+ }
206
+ } catch (err) {
207
+ console.error(`ipg: ${(err as Error).message}`);
208
+ return 1;
209
+ }
210
+ }
211
+
212
+ process.exitCode = await main(process.argv.slice(2));