@0tarun0709/pi-pocket 0.0.0-stage → 0.1.2
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/CHANGELOG.md +40 -0
- package/LICENSE +21 -0
- package/README.md +76 -2
- package/extensions/pocket/auth.ts +74 -0
- package/extensions/pocket/index.ts +473 -0
- package/extensions/pocket/tailscale.ts +43 -0
- package/package.json +51 -4
- package/web/index.html +381 -0
- package/web/pair.html +67 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.2] - 2026-11-21
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- GitHub Actions workflow for staging npm releases with trusted publishing and
|
|
14
|
+
maintainer approval.
|
|
15
|
+
|
|
16
|
+
## [0.1.1] - 2026-11-21
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- npm installation as `@0tarun0709/pi-pocket`.
|
|
21
|
+
- A changelog included in the package.
|
|
22
|
+
|
|
23
|
+
## [0.1.0] - 2026-11-21
|
|
24
|
+
|
|
25
|
+
### Added
|
|
26
|
+
|
|
27
|
+
- Browser interface for a running Pi session, with streamed responses, Markdown,
|
|
28
|
+
themes, and expandable tool activity.
|
|
29
|
+
- On-demand laptop access with `/remote` and private phone access with
|
|
30
|
+
`/remote pair` through Tailscale Serve.
|
|
31
|
+
- Short-lived QR pairing codes, persistent browser credentials, and individual
|
|
32
|
+
browser revocation.
|
|
33
|
+
- Controls to stop execution, disconnect Tailscale access, or perform an
|
|
34
|
+
emergency stop and disable Pi Pocket.
|
|
35
|
+
- Installable Pi package, setup and security documentation, and MIT license.
|
|
36
|
+
|
|
37
|
+
[Unreleased]: https://github.com/0Tarun0709/pi-pocket/compare/v0.1.2...HEAD
|
|
38
|
+
[0.1.2]: https://github.com/0Tarun0709/pi-pocket/compare/v0.1.1...v0.1.2
|
|
39
|
+
[0.1.1]: https://github.com/0Tarun0709/pi-pocket/compare/v0.1.0...v0.1.1
|
|
40
|
+
[0.1.0]: https://github.com/0Tarun0709/pi-pocket/releases/tag/v0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Musham Sai Tarun
|
|
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,77 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Pi Pocket
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@0tarun0709/pi-pocket)
|
|
4
|
+
[](https://www.npmjs.com/package/@earendil-works/pi-coding-agent)
|
|
5
|
+
[](https://nodejs.org/)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
|
|
8
|
+
Access your running [Pi](https://github.com/earendil-works/pi) session from a browser, locally or privately through Tailscale. View responses and tool activity, send prompts, and stop a running agent.
|
|
9
|
+
|
|
10
|
+
See the [changelog](CHANGELOG.md) for release history.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
Requires Pi and Node.js 24 or newer.
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
pi install npm:@0tarun0709/pi-pocket
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Alternatively, install from Git with `pi install git:github.com/0Tarun0709/pi-pocket`.
|
|
21
|
+
|
|
22
|
+
Restart Pi or run `/reload`. Pi Pocket does not start a server until you request access.
|
|
23
|
+
|
|
24
|
+
## Use on your laptop
|
|
25
|
+
|
|
26
|
+
Run `/remote` in Pi, then open **http://127.0.0.1:18790** on the laptop. Local access does not require pairing.
|
|
27
|
+
|
|
28
|
+
## Use on your phone
|
|
29
|
+
|
|
30
|
+
1. Install Tailscale on both devices and connect them to the same tailnet.
|
|
31
|
+
2. Run `/remote pair` in Pi on the laptop.
|
|
32
|
+
3. Scan the QR code with your phone to pair its browser.
|
|
33
|
+
|
|
34
|
+
Your laptop must remain awake, online, and running Pi. Pi Pocket starts or reuses a private Tailscale Serve route; it never enables Funnel. If Tailscale asks an administrator to enable Serve, follow the displayed link and run `/remote pair` again.
|
|
35
|
+
|
|
36
|
+
The QR code is a secret: it expires after two minutes, works once, and is invalidated when you generate another. If you can't scan it, press `c` to see the address and pairing code. Run `/remote devices` on the laptop to revoke a paired browser; its ID appears in the Sessions menu. Pairing lasts up to one year and is lost if the browser's data is cleared.
|
|
37
|
+
|
|
38
|
+
## Session controls
|
|
39
|
+
|
|
40
|
+
- **Stop execution** requests that Pi stop the current run without disconnecting.
|
|
41
|
+
- **Sessions → Turn off Tailscale access** disconnects devices using the Pi Pocket Serve route. Pi keeps running, and any enabled local access stays available. Run `/remote pair` on the laptop to reconnect. If Serve is shared with another route, Pi Pocket won't remove it automatically. If the phone disconnects before confirming success, check `tailscale serve status` on the laptop.
|
|
42
|
+
- **Sessions → Stop all & disconnect** aborts the run, discards queued Pi Pocket prompts, and disables the server persistently. On the laptop, run `/remote enable`, then `/remote` or `/remote pair` to start again. It cannot undo completed actions or immediately stop tools that ignore cancellation.
|
|
43
|
+
|
|
44
|
+
Session switching and answering Pi's interactive dialogs from the browser are not yet supported. Answer those dialogs in the laptop terminal.
|
|
45
|
+
|
|
46
|
+
## Security
|
|
47
|
+
|
|
48
|
+
- The unauthenticated local listener is bound to `127.0.0.1:18790`. **Never proxy or expose this port.** Other processes on the laptop can access it.
|
|
49
|
+
- Tailscale access uses the separate, authenticated listener on port `18789`. Only `/remote pair` enables it. Keep pairing codes and paired devices private.
|
|
50
|
+
- Both ports are reserved while Pi Pocket is running; an access method not enabled returns HTTP 503. Only one Pi session can use them at a time.
|
|
51
|
+
- If HTTPS port 443 is already used by another service or Funnel is configured, Pi Pocket refuses to change Serve. Check `tailscale serve status` on the laptop and avoid changing Serve settings concurrently while pairing.
|
|
52
|
+
- Browser credential hashes and the emergency lock are stored under `~/.pi/agent/pi-pocket/`, or `PI_CODING_AGENT_DIR` if set. Device labels are browser-reported, not verified identities.
|
|
53
|
+
|
|
54
|
+
## Development
|
|
55
|
+
|
|
56
|
+
Clone the repository, run `npm ci`, and start Pi in the project directory. Grant project trust when prompted. The project package loads through `.pi/settings.json`; use `/reload` after changes. Disable a globally installed copy while developing to avoid a port conflict.
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
npm test
|
|
60
|
+
npm run typecheck
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Publishing
|
|
64
|
+
|
|
65
|
+
Non-prerelease GitHub releases trigger `.github/workflows/publish.yml`.
|
|
66
|
+
The release tag must match the package version (for example, `v0.1.2` for
|
|
67
|
+
`0.1.2`). The workflow runs checks and stages the package on npm; a maintainer
|
|
68
|
+
must review and approve it with 2FA before it is published.
|
|
69
|
+
|
|
70
|
+
Configure npm Trusted Publishing for `0Tarun0709/pi-pocket` with workflow
|
|
71
|
+
filename `publish.yml`. Direct `npm publish` permission is not needed. A new
|
|
72
|
+
trusted publisher must complete its first successful publish within two days,
|
|
73
|
+
so configure it shortly before a release.
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
type Browser = { id: string; hash: string; created: string; expires: number; label: string };
|
|
6
|
+
const lifetime = 365 * 24 * 60 * 60 * 1000;
|
|
7
|
+
const digest = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
8
|
+
|
|
9
|
+
export class Pairing {
|
|
10
|
+
private readonly file: string;
|
|
11
|
+
private readonly dir: string;
|
|
12
|
+
private browsers: Browser[];
|
|
13
|
+
private pending?: { code: string; expires: number };
|
|
14
|
+
|
|
15
|
+
constructor(dir: string) {
|
|
16
|
+
this.dir = dir;
|
|
17
|
+
this.file = join(dir, "browsers.json");
|
|
18
|
+
try {
|
|
19
|
+
const value: unknown = JSON.parse(readFileSync(this.file, "utf8"));
|
|
20
|
+
if (!Array.isArray(value) || !value.every((item) => item && /^[a-f0-9]{16}$/.test(item.id) && /^[a-f0-9]{64}$/.test(item.hash) && typeof item.created === "string" && Number.isSafeInteger(item.expires))) throw new Error("Invalid paired browsers file");
|
|
21
|
+
this.browsers = value;
|
|
22
|
+
} catch (error: any) {
|
|
23
|
+
if (error.code !== "ENOENT") throw error;
|
|
24
|
+
this.browsers = [];
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
private save(browsers: Browser[]) {
|
|
29
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
30
|
+
const temporary = join(this.dir, `.browsers-${randomBytes(12).toString("hex")}`);
|
|
31
|
+
try {
|
|
32
|
+
writeFileSync(temporary, JSON.stringify(browsers), { mode: 0o600, flag: "wx" });
|
|
33
|
+
renameSync(temporary, this.file);
|
|
34
|
+
this.browsers = browsers;
|
|
35
|
+
} finally {
|
|
36
|
+
try { unlinkSync(temporary); } catch (error: any) { if (error.code !== "ENOENT") throw error; }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
issue() {
|
|
41
|
+
this.pending = { code: randomBytes(24).toString("base64url"), expires: Date.now() + 120_000 };
|
|
42
|
+
return this.pending.code;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
accept(code: unknown, userAgent = "") {
|
|
46
|
+
const pending = this.pending;
|
|
47
|
+
if (typeof code !== "string" || !pending || Date.now() >= pending.expires) return undefined;
|
|
48
|
+
const given = Buffer.from(code);
|
|
49
|
+
const expected = Buffer.from(pending.code);
|
|
50
|
+
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return undefined;
|
|
51
|
+
this.pending = undefined;
|
|
52
|
+
const token = randomBytes(32).toString("base64url");
|
|
53
|
+
const created = new Date().toISOString();
|
|
54
|
+
const label = /iPhone|iPad/i.test(userAgent) ? "iPhone or iPad" : /Android/i.test(userAgent) ? "Android" : /Macintosh/i.test(userAgent) ? "Mac" : /Windows/i.test(userAgent) ? "Windows" : /Linux/i.test(userAgent) ? "Linux" : "Unknown";
|
|
55
|
+
const browser = { id: randomBytes(8).toString("hex"), hash: digest(token), created, expires: Date.now() + lifetime, label };
|
|
56
|
+
this.save([...this.browsers.filter((item) => item.expires > Date.now()), browser]);
|
|
57
|
+
return token;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
identify(token: string | undefined) {
|
|
61
|
+
if (typeof token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(token)) return undefined;
|
|
62
|
+
const hash = digest(token);
|
|
63
|
+
const browser = this.browsers.find((item) => item.expires > Date.now() && item.hash === hash);
|
|
64
|
+
return browser ? this.describe(browser) : undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private describe({ id, created, label }: Browser) {
|
|
68
|
+
return { id, created, label: typeof label === "string" && /^(iPhone or iPad|Android|Mac|Windows|Linux|Unknown)$/.test(label) ? label : "Unknown" };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
list() { return this.browsers.filter((browser) => browser.expires > Date.now()).map((browser) => this.describe(browser)); }
|
|
72
|
+
|
|
73
|
+
revoke(id: string) { this.save(this.browsers.filter((browser) => browser.id !== id)); }
|
|
74
|
+
}
|
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
import { createServer, type Server } from "node:http";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { readFile, writeFile, unlink, mkdir } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { createRequire } from "node:module";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import { Pairing } from "./auth.ts";
|
|
11
|
+
import { prepareTailscale } from "./tailscale.ts";
|
|
12
|
+
|
|
13
|
+
const page = fileURLToPath(new URL("../../web/index.html", import.meta.url));
|
|
14
|
+
const require = createRequire(import.meta.url);
|
|
15
|
+
const QRCode: typeof import("qrcode") = require("qrcode");
|
|
16
|
+
const execFileAsync = promisify(execFile);
|
|
17
|
+
const port = 18789;
|
|
18
|
+
const localPort = 18790;
|
|
19
|
+
const stateDir = join(process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"), "pi-pocket");
|
|
20
|
+
const disabledFile = join(stateDir, "remote-disabled");
|
|
21
|
+
const originFile = join(stateDir, "tailscale-origin");
|
|
22
|
+
|
|
23
|
+
type ToolMessage = { role: "tool"; id: string; name: string; args: unknown; output?: unknown; state: "running" | "done" | "error" | "unknown" };
|
|
24
|
+
type DisplayMessage = { role: "user" | "assistant"; text: string } | { role: "source"; via: "tailscale" | "local" } | ToolMessage;
|
|
25
|
+
|
|
26
|
+
function display(message: any): DisplayMessage | undefined {
|
|
27
|
+
if (message?.role !== "user" && message?.role !== "assistant") return;
|
|
28
|
+
const text = typeof message.content === "string" ? message.content :
|
|
29
|
+
message.content?.filter((part: any) => part.type === "text").map((part: any) => part.text).join("\n");
|
|
30
|
+
if (text) return { role: message.role as "user" | "assistant", text };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export default function (pi: ExtensionAPI) {
|
|
34
|
+
let server: Server | undefined;
|
|
35
|
+
let localServer: Server | undefined;
|
|
36
|
+
let messages: DisplayMessage[] = [];
|
|
37
|
+
let streaming: DisplayMessage | undefined;
|
|
38
|
+
let waiting: { kind: string; title?: string } | undefined;
|
|
39
|
+
let disabled = false;
|
|
40
|
+
let queued: { text: string; via: "tailscale" | "local" }[] = [];
|
|
41
|
+
let queueTimer: ReturnType<typeof setInterval> | undefined;
|
|
42
|
+
let pairing = new Pairing(stateDir);
|
|
43
|
+
let remoteOrigin: string | undefined;
|
|
44
|
+
let disconnectingTailscale = false;
|
|
45
|
+
let sessionActive = false;
|
|
46
|
+
let generation = 0;
|
|
47
|
+
let localEnabled = false;
|
|
48
|
+
let remoteEnabled = false;
|
|
49
|
+
let starting = false;
|
|
50
|
+
|
|
51
|
+
function stopServer() {
|
|
52
|
+
generation++;
|
|
53
|
+
localEnabled = false;
|
|
54
|
+
remoteEnabled = false;
|
|
55
|
+
if (queueTimer) clearInterval(queueTimer);
|
|
56
|
+
queueTimer = undefined;
|
|
57
|
+
const active = [server, localServer];
|
|
58
|
+
server = undefined;
|
|
59
|
+
localServer = undefined;
|
|
60
|
+
for (const listener of active) if (listener) { listener.close(); listener.closeAllConnections(); }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function ensureEnabled() {
|
|
64
|
+
if (!sessionActive || disabled) throw new Error("Pi Pocket is disabled. Use /remote enable first.");
|
|
65
|
+
try {
|
|
66
|
+
await readFile(disabledFile);
|
|
67
|
+
disabled = true;
|
|
68
|
+
stopServer();
|
|
69
|
+
throw new Error("Pi Pocket is disabled. Use /remote enable first.");
|
|
70
|
+
} catch (error: any) { if (error.code !== "ENOENT") throw error; }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function tool(id: string) {
|
|
74
|
+
return messages.find((item): item is ToolMessage => item.role === "tool" && item.id === id);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function loadHistory(entries: ReturnType<import("@earendil-works/pi-coding-agent").SessionManager["getBranch"]>) {
|
|
78
|
+
messages = [];
|
|
79
|
+
for (const entry of entries) {
|
|
80
|
+
if (entry.type === "custom" && entry.customType === "pi-pocket-prompt") {
|
|
81
|
+
const via = (entry.data as { via?: unknown } | undefined)?.via;
|
|
82
|
+
if (via === "tailscale" || via === "local") messages.push({ role: "source", via });
|
|
83
|
+
}
|
|
84
|
+
if (entry.type !== "message") continue;
|
|
85
|
+
const message = entry.message;
|
|
86
|
+
const item = display(message);
|
|
87
|
+
if (item) messages.push(item);
|
|
88
|
+
if (message.role === "assistant") {
|
|
89
|
+
for (const part of message.content) {
|
|
90
|
+
if (part.type === "toolCall") messages.push({ role: "tool", id: part.id, name: part.name, args: part.arguments, state: "unknown" });
|
|
91
|
+
}
|
|
92
|
+
} else if (message.role === "toolResult") {
|
|
93
|
+
const existing = tool(message.toolCallId);
|
|
94
|
+
if (existing) Object.assign(existing, { output: { content: message.content, details: message.details }, state: message.isError ? "error" : "done" });
|
|
95
|
+
else messages.push({ role: "tool", id: message.toolCallId, name: message.toolName, args: undefined, output: { content: message.content, details: message.details }, state: message.isError ? "error" : "done" });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
streaming = undefined;
|
|
99
|
+
waiting = undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
pi.registerEntryRenderer("pi-pocket-prompt", (entry, _options, theme) => {
|
|
103
|
+
const label = (entry.data as { via?: string } | undefined)?.via === "tailscale"
|
|
104
|
+
? "↳ Pi Pocket · Tailscale address"
|
|
105
|
+
: "↳ Pi Pocket · local address";
|
|
106
|
+
return { render: (width: number) => [theme.fg("dim", label.slice(0, Math.max(0, width)))], invalidate() {} };
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
pi.registerCommand("remote", {
|
|
110
|
+
description: "Show the local address; use /remote pair for Tailscale access",
|
|
111
|
+
handler: async (args, ctx) => {
|
|
112
|
+
const input = args.trim();
|
|
113
|
+
if (input === "pair" || input === "pair local") {
|
|
114
|
+
if (!sessionActive) { ctx.ui.notify("Pi Pocket is not available in this session.", "error"); return; }
|
|
115
|
+
if (disabled) { ctx.ui.notify("Pi Pocket is disabled. Use /remote enable first.", "error"); return; }
|
|
116
|
+
let origin: string | undefined;
|
|
117
|
+
let reserved = false;
|
|
118
|
+
try {
|
|
119
|
+
await ensureEnabled();
|
|
120
|
+
await startServer(ctx, false, false);
|
|
121
|
+
reserved = true;
|
|
122
|
+
if (input === "pair") remoteEnabled = false;
|
|
123
|
+
const startingGeneration = generation;
|
|
124
|
+
if (input === "pair") {
|
|
125
|
+
ctx.ui.notify("Preparing private Tailscale access…", "info");
|
|
126
|
+
origin = await prepareTailscale(port);
|
|
127
|
+
if (!sessionActive || disabled || generation !== startingGeneration) throw new Error("Pi Pocket stopped during setup.");
|
|
128
|
+
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
129
|
+
await writeFile(originFile, origin, { mode: 0o600 });
|
|
130
|
+
if (!sessionActive || disabled || generation !== startingGeneration) throw new Error("Pi Pocket stopped during setup.");
|
|
131
|
+
remoteOrigin = origin;
|
|
132
|
+
}
|
|
133
|
+
await startServer(ctx, false);
|
|
134
|
+
const address = server?.address();
|
|
135
|
+
if (!address || typeof address === "string") throw new Error("Pi Pocket is not running.");
|
|
136
|
+
origin ??= `http://127.0.0.1:${address.port}`;
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (reserved && !localEnabled && !remoteEnabled) stopServer();
|
|
139
|
+
ctx.ui.notify(`Pi Pocket could not start pairing: ${error}\nCheck Tailscale Serve on the laptop before retrying.`, "error");
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const code = pairing.issue();
|
|
143
|
+
const qr = QRCode.create(`${origin}/pair#pair=${code}`, { errorCorrectionLevel: "L" });
|
|
144
|
+
const size = qr.modules.size + 8;
|
|
145
|
+
const black = (y: number, x: number) => y >= 4 && x >= 4 && y < size - 4 && x < size - 4 && qr.modules.get(y - 4, x - 4);
|
|
146
|
+
const rows: string[] = [];
|
|
147
|
+
for (let y = 0; y < size; y += 2) {
|
|
148
|
+
let row = "";
|
|
149
|
+
for (let x = 0; x < size; x++) row += black(y, x) ? (black(y + 1, x) ? "█" : "▀") : (black(y + 1, x) ? "▄" : " ");
|
|
150
|
+
rows.push(`\x1b[30;47m${row}\x1b[0m`);
|
|
151
|
+
}
|
|
152
|
+
let showCode = false;
|
|
153
|
+
await ctx.ui.custom<void>((tui, theme, keys, done) => ({
|
|
154
|
+
render(width) {
|
|
155
|
+
const height = tui.terminal?.rows ?? Infinity;
|
|
156
|
+
const codeWidth = Math.max(1, width - 6);
|
|
157
|
+
const codeLines: string[] = [];
|
|
158
|
+
for (let i = 0; i < code.length; i += codeWidth) codeLines.push(`${i ? " " : "Code: "}${code.slice(i, i + codeWidth)}`.slice(0, width));
|
|
159
|
+
const addressLines: string[] = [];
|
|
160
|
+
const addressWidth = Math.max(1, width - 9);
|
|
161
|
+
for (let i = 0; i < origin.length; i += addressWidth) addressLines.push(`${i ? " " : "Address: "}${origin.slice(i, i + addressWidth)}`.slice(0, width));
|
|
162
|
+
const fits = width >= size && height >= rows.length + 1;
|
|
163
|
+
if (fits && !showCode) {
|
|
164
|
+
const title = origin.startsWith("https://") ? "Scan QR · c: code · Esc: close · expires in 2 min" : "Local pairing · c: code · Esc: close · expires in 2 min";
|
|
165
|
+
return [theme.fg("accent", title.slice(0, width)), ...rows, ...(height >= rows.length + codeLines.length + addressLines.length + 2 ? [...codeLines, ...addressLines, "Enter or Esc to close".slice(0, width)] : [])];
|
|
166
|
+
}
|
|
167
|
+
return [theme.fg("accent", "Pairing code · expires in 2 minutes".slice(0, width)), ...codeLines, ...addressLines, (fits ? "c: QR · Esc: close" : "Enlarge terminal for QR · Esc: close").slice(0, width)];
|
|
168
|
+
},
|
|
169
|
+
handleInput(data) {
|
|
170
|
+
if (data === "c") { showCode = !showCode; tui.requestRender(); }
|
|
171
|
+
else if (keys.matches(data, "tui.select.confirm") || keys.matches(data, "tui.select.cancel")) done();
|
|
172
|
+
},
|
|
173
|
+
invalidate() {},
|
|
174
|
+
}), { overlay: true, overlayOptions: { width: "100%", maxHeight: "100%" } });
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (input === "devices") {
|
|
178
|
+
const owner = server;
|
|
179
|
+
if (!owner?.listening) { ctx.ui.notify("Pi Pocket is not running in this session. Manage browsers in the session that owns the server.", "error"); return; }
|
|
180
|
+
const browsers = pairing.list();
|
|
181
|
+
if (!browsers.length) { ctx.ui.notify("No paired browsers.", "info"); return; }
|
|
182
|
+
const options = browsers.map((browser) => `${browser.label} · ${browser.id} · paired ${browser.created.slice(0, 10)}`);
|
|
183
|
+
const selected = await ctx.ui.select("Select a browser to revoke", options);
|
|
184
|
+
const index = selected ? options.indexOf(selected) : -1;
|
|
185
|
+
if (index >= 0 && await ctx.ui.confirm("Revoke browser?", `This will disconnect ${options[index]}.`)) {
|
|
186
|
+
if (server !== owner || !owner.listening) { ctx.ui.notify("Pi Pocket stopped; browser was not revoked.", "error"); return; }
|
|
187
|
+
pairing.revoke(browsers[index].id);
|
|
188
|
+
ctx.ui.notify("Browser revoked.", "info");
|
|
189
|
+
}
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (input === "unshare") {
|
|
193
|
+
try {
|
|
194
|
+
await unlink(originFile).catch((error) => { if (error.code !== "ENOENT") throw error; });
|
|
195
|
+
remoteOrigin = undefined;
|
|
196
|
+
ctx.ui.notify("Pi Pocket no longer accepts the Tailscale hostname. Disable Tailscale Serve separately.", "info");
|
|
197
|
+
} catch (error) { ctx.ui.notify(`Pi Pocket could not remove its origin: ${error}`, "error"); }
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (input.startsWith("share ")) {
|
|
201
|
+
const hostname = input.slice(6).toLowerCase();
|
|
202
|
+
if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.ts\.net$/.test(hostname) || hostname.length > 253) {
|
|
203
|
+
ctx.ui.notify("Provide the exact Tailscale hostname, without https:// or a port.", "error");
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
208
|
+
await writeFile(originFile, `https://${hostname}`, { mode: 0o600 });
|
|
209
|
+
remoteOrigin = `https://${hostname}`;
|
|
210
|
+
ctx.ui.notify(`Pi Pocket accepts ${remoteOrigin}. Run /remote pair to pair a browser.`, "info");
|
|
211
|
+
} catch (error) { ctx.ui.notify(`Pi Pocket could not save its origin: ${error}`, "error"); }
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (input === "enable") {
|
|
215
|
+
try {
|
|
216
|
+
await unlink(join(ctx.cwd, ".pi", "remote-disabled")).catch((error) => { if (error.code !== "ENOENT") throw error; });
|
|
217
|
+
await unlink(disabledFile).catch((error) => { if (error.code !== "ENOENT") throw error; });
|
|
218
|
+
disabled = false;
|
|
219
|
+
ctx.ui.notify("Pi Pocket enabled. Use /remote for local access or /remote pair for Tailscale.", "info");
|
|
220
|
+
} catch (error) { ctx.ui.notify(`Pi Pocket could not enable: ${error}`, "error"); }
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (input) { ctx.ui.notify("Use /remote for local access, /remote pair for Tailscale, or /remote devices to manage browsers.", "info"); return; }
|
|
224
|
+
if (disabled) { ctx.ui.notify("Pi Pocket is disabled. Use /remote enable first.", "error"); return; }
|
|
225
|
+
try { await startServer(ctx, true); }
|
|
226
|
+
catch (error) { ctx.ui.notify(`Pi Pocket could not start: ${error}`, "error"); return; }
|
|
227
|
+
const address = localServer?.address();
|
|
228
|
+
ctx.ui.notify(address && typeof address !== "string" ? `Pi Pocket: http://127.0.0.1:${address.port}\nUse /remote pair for Tailscale access.` : "Pi Pocket is not running", "info");
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
async function startServer(ctx: import("@earendil-works/pi-coding-agent").ExtensionContext, isLocal: boolean, activate = true) {
|
|
233
|
+
await ensureEnabled();
|
|
234
|
+
const startingGeneration = generation;
|
|
235
|
+
if (starting) throw new Error("Pi Pocket is already starting. Try again.");
|
|
236
|
+
if (server && localServer) {
|
|
237
|
+
if (activate) {
|
|
238
|
+
if (isLocal) localEnabled = true; else remoteEnabled = true;
|
|
239
|
+
const address = (isLocal ? localServer : server).address();
|
|
240
|
+
if (address && typeof address !== "string") ctx.ui.notify(`${isLocal ? "Pi Pocket local" : "Pi Remote"}: http://127.0.0.1:${address.port}`, "info");
|
|
241
|
+
}
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
starting = true;
|
|
245
|
+
try { await startListeners(ctx, isLocal, startingGeneration, activate); }
|
|
246
|
+
finally { starting = false; }
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async function startListeners(ctx: import("@earendil-works/pi-coding-agent").ExtensionContext, isLocal: boolean, startingGeneration: number, activate: boolean) {
|
|
250
|
+
pairing = new Pairing(stateDir);
|
|
251
|
+
const [html, pairPage, marked, dompurify, highlight] = await Promise.all([
|
|
252
|
+
readFile(page),
|
|
253
|
+
readFile(new URL("../../web/pair.html", import.meta.url)),
|
|
254
|
+
readFile(join(dirname(require.resolve("marked")), "marked.umd.js")),
|
|
255
|
+
readFile(join(dirname(require.resolve("dompurify")), "purify.min.js")),
|
|
256
|
+
readFile(require.resolve("@highlightjs/cdn-assets/highlight.min.js")),
|
|
257
|
+
]);
|
|
258
|
+
const handler = (isLocal: boolean) => async (req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => {
|
|
259
|
+
const host = req.headers.host;
|
|
260
|
+
const address = (isLocal ? localServer : server)?.address();
|
|
261
|
+
const expectedHost = typeof address === "object" && address ? `127.0.0.1:${address.port}` : "";
|
|
262
|
+
const localOrigin = `http://${expectedHost}`;
|
|
263
|
+
const requestOrigin = host === expectedHost ? localOrigin : !isLocal && remoteOrigin && host === new URL(remoteOrigin).host ? remoteOrigin : undefined;
|
|
264
|
+
if (!requestOrigin || (req.headers.origin && req.headers.origin !== requestOrigin)) {
|
|
265
|
+
res.writeHead(403).end();
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
if (disabled || (isLocal ? !localEnabled : !remoteEnabled)) { res.writeHead(503).end("Pi Pocket is not active for this address."); return; }
|
|
269
|
+
res.setHeader("Cache-Control", "no-store");
|
|
270
|
+
const cookieName = requestOrigin === localOrigin ? "pi-pocket-local" : "__Host-pi-pocket";
|
|
271
|
+
const cookie = req.headers.cookie?.split(";").map((part) => part.trim()).find((part) => part.startsWith(`${cookieName}=`))?.slice(cookieName.length + 1);
|
|
272
|
+
const browser = pairing.identify(cookie);
|
|
273
|
+
if (!isLocal && req.method === "POST" && req.url === "/api/pair") {
|
|
274
|
+
if (req.headers.origin !== requestOrigin || req.headers["content-type"] !== "application/json") { res.writeHead(403).end(); return; }
|
|
275
|
+
let body = "";
|
|
276
|
+
for await (const chunk of req) { body += chunk; if (body.length > 1024) { res.writeHead(413).end(); return; } }
|
|
277
|
+
try {
|
|
278
|
+
const token = pairing.accept(JSON.parse(body).code, req.headers["user-agent"]);
|
|
279
|
+
if (!token) { res.writeHead(401).end("Invalid or expired pairing code."); return; }
|
|
280
|
+
res.setHeader("Set-Cookie", `${cookieName}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=31536000${requestOrigin === localOrigin ? "" : "; Secure"}`);
|
|
281
|
+
res.writeHead(200).end();
|
|
282
|
+
} catch (error) {
|
|
283
|
+
ctx.ui.notify(`Pi Pocket pairing failed: ${error}`, "error");
|
|
284
|
+
res.writeHead(400).end("Could not complete pairing. Generate a new code on the laptop.");
|
|
285
|
+
}
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (req.method === "GET" && (req.url === "/" || req.url === "/pair")) {
|
|
289
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
290
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(isLocal || (browser && req.url === "/") ? html : pairPage);
|
|
291
|
+
} else if (!isLocal && !browser) {
|
|
292
|
+
res.writeHead(401).end("Pair this browser using /remote pair on the laptop.");
|
|
293
|
+
} else if (req.method === "GET" && (req.url === "/marked.js" || req.url === "/purify.js" || req.url === "/highlight.js")) {
|
|
294
|
+
res.writeHead(200, { "Content-Type": "text/javascript; charset=utf-8" }).end(req.url === "/marked.js" ? marked : req.url === "/purify.js" ? dompurify : highlight);
|
|
295
|
+
} else if (req.method === "GET" && req.url === "/api/session") {
|
|
296
|
+
res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({
|
|
297
|
+
messages: streaming ? [...messages, streaming] : messages,
|
|
298
|
+
busy: !ctx.isIdle(),
|
|
299
|
+
waiting,
|
|
300
|
+
queued: queued.length,
|
|
301
|
+
browser,
|
|
302
|
+
local: isLocal,
|
|
303
|
+
}));
|
|
304
|
+
} else if (req.method === "POST" && req.url === "/api/prompt") {
|
|
305
|
+
if (req.headers.origin !== requestOrigin || req.headers["content-type"] !== "application/json") {
|
|
306
|
+
res.writeHead(403).end();
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
let body = "";
|
|
310
|
+
for await (const chunk of req) {
|
|
311
|
+
body += chunk;
|
|
312
|
+
if (body.length > 64_000) { res.writeHead(413).end(); return; }
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
const { text } = JSON.parse(body);
|
|
316
|
+
if (typeof text !== "string" || !text.trim()) throw new Error("Empty prompt");
|
|
317
|
+
if (disabled) { res.writeHead(503).end("Pi Remote disabled"); return; }
|
|
318
|
+
queued.push({ text: text.trim(), via: !isLocal && requestOrigin === remoteOrigin ? "tailscale" : "local" });
|
|
319
|
+
res.writeHead(202).end();
|
|
320
|
+
} catch {
|
|
321
|
+
res.writeHead(400).end("Invalid prompt");
|
|
322
|
+
}
|
|
323
|
+
} else if (req.method === "POST" && req.url === "/api/disconnect-tailscale") {
|
|
324
|
+
if (req.headers.origin !== requestOrigin || req.headers["content-type"] !== "application/json") {
|
|
325
|
+
res.writeHead(403).end();
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (!remoteOrigin || disconnectingTailscale) {
|
|
329
|
+
res.writeHead(409).end("Tailscale access is not configured or is already being disconnected.");
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
disconnectingTailscale = true;
|
|
333
|
+
let routeRemoved = false;
|
|
334
|
+
try {
|
|
335
|
+
const { stdout } = await execFileAsync("tailscale", ["serve", "status", "--json"], { timeout: 10000, maxBuffer: 1024 * 1024 });
|
|
336
|
+
const config = JSON.parse(stdout);
|
|
337
|
+
const host = `${new URL(remoteOrigin).hostname}:443`;
|
|
338
|
+
const handlers = config.Web?.[host]?.Handlers;
|
|
339
|
+
// Never remove a shared listener or any route other than this package's root proxy.
|
|
340
|
+
if (Object.keys(config.Web ?? {}).length !== 1 || Object.keys(config.TCP ?? {}).length !== 1 ||
|
|
341
|
+
Object.keys(config.TCP?.["443"] ?? {}).join() !== "HTTPS" || config.TCP["443"].HTTPS !== true ||
|
|
342
|
+
!handlers || Object.keys(handlers).join() !== "/" || Object.keys(handlers["/"] ?? {}).join() !== "Proxy" ||
|
|
343
|
+
handlers["/"].Proxy !== `http://127.0.0.1:${port}` || Object.values(config.AllowFunnel ?? {}).some(Boolean)) {
|
|
344
|
+
res.writeHead(409).end("Serve configuration does not exclusively match Pi Pocket. Check it on the laptop.");
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
await execFileAsync("tailscale", ["serve", "--https=443", "off"], { timeout: 10000, maxBuffer: 1024 * 1024 });
|
|
348
|
+
routeRemoved = true;
|
|
349
|
+
remoteOrigin = undefined;
|
|
350
|
+
await unlink(originFile).catch((error) => { if (error.code !== "ENOENT") throw error; });
|
|
351
|
+
res.writeHead(200).end("Tailscale access turned off.");
|
|
352
|
+
} catch (error) {
|
|
353
|
+
ctx.ui.notify(`Pi Pocket could not finish disabling Tailscale access: ${error}`, "error");
|
|
354
|
+
res.writeHead(500).end(routeRemoved ? "Serve is off, but Pi Pocket could not save its settings. Check the laptop." : "Could not turn off Tailscale Serve. Check the laptop.");
|
|
355
|
+
} finally {
|
|
356
|
+
disconnectingTailscale = false;
|
|
357
|
+
}
|
|
358
|
+
} else if (req.method === "POST" && (req.url === "/api/stop" || req.url === "/api/stop-all")) {
|
|
359
|
+
if (req.headers.origin !== requestOrigin || req.headers["content-type"] !== "application/json") {
|
|
360
|
+
res.writeHead(403).end();
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
if (req.url === "/api/stop-all") {
|
|
364
|
+
disabled = true;
|
|
365
|
+
queued = [];
|
|
366
|
+
ctx.abort();
|
|
367
|
+
let closed = false;
|
|
368
|
+
const closeOnce = () => { if (!closed) { closed = true; stopServer(); } };
|
|
369
|
+
res.once("finish", closeOnce);
|
|
370
|
+
res.once("close", closeOnce);
|
|
371
|
+
try {
|
|
372
|
+
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
373
|
+
await writeFile(disabledFile, "Pi Remote disabled. Use /remote enable to restart.\n", { mode: 0o600 });
|
|
374
|
+
res.writeHead(200).end();
|
|
375
|
+
} catch (error) {
|
|
376
|
+
ctx.ui.notify(`Pi Remote disabled, but could not persist the lock: ${error}`, "error");
|
|
377
|
+
res.writeHead(500).end("Disabled until restart, but could not save the lock");
|
|
378
|
+
}
|
|
379
|
+
} else {
|
|
380
|
+
ctx.abort();
|
|
381
|
+
res.writeHead(200).end();
|
|
382
|
+
}
|
|
383
|
+
} else {
|
|
384
|
+
res.writeHead(404).end();
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
if (!sessionActive || disabled || generation !== startingGeneration) throw new Error("Pi Pocket stopped during startup.");
|
|
388
|
+
server = createServer(handler(false));
|
|
389
|
+
localServer = createServer(handler(true));
|
|
390
|
+
const remote = server, local = localServer;
|
|
391
|
+
for (const listener of [remote, local]) listener.on("error", (error) => ctx.ui.notify(`Pi Remote: ${error.message}`, "error"));
|
|
392
|
+
try {
|
|
393
|
+
for (const [listener, listenPort] of [[remote, port], [local, localPort]] as const) {
|
|
394
|
+
await new Promise<void>((resolve, reject) => {
|
|
395
|
+
listener.once("error", reject);
|
|
396
|
+
listener.listen(listenPort, "127.0.0.1", () => resolve());
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
await ensureEnabled();
|
|
400
|
+
if (!sessionActive || disabled || generation !== startingGeneration || server !== remote || localServer !== local) throw new Error("Pi Pocket stopped during startup.");
|
|
401
|
+
} catch (error) { stopServer(); throw error; }
|
|
402
|
+
if (activate) { if (isLocal) localEnabled = true; else remoteEnabled = true; }
|
|
403
|
+
const address = (isLocal ? local : remote).address();
|
|
404
|
+
if (activate && address && typeof address !== "string") ctx.ui.notify(`${isLocal ? "Pi Pocket local" : "Pi Remote"}: http://127.0.0.1:${address.port}`, "info");
|
|
405
|
+
if (!queueTimer) queueTimer = setInterval(() => {
|
|
406
|
+
if (!disabled && queued.length && ctx.isIdle()) {
|
|
407
|
+
const prompt = queued.shift()!;
|
|
408
|
+
try {
|
|
409
|
+
pi.appendEntry("pi-pocket-prompt", { via: prompt.via });
|
|
410
|
+
messages.push({ role: "source", via: prompt.via });
|
|
411
|
+
pi.sendUserMessage(prompt.text);
|
|
412
|
+
} catch (error) { queued.unshift(prompt); ctx.ui.notify(`Pi Remote could not send: ${error}`, "error"); }
|
|
413
|
+
}
|
|
414
|
+
}, 250);
|
|
415
|
+
queueTimer.unref();
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
419
|
+
sessionActive = true;
|
|
420
|
+
generation++;
|
|
421
|
+
loadHistory(ctx.sessionManager.getBranch());
|
|
422
|
+
try {
|
|
423
|
+
const configured = await readFile(originFile, "utf8");
|
|
424
|
+
if (!/^https:\/\/[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.ts\.net$/.test(configured)) throw new Error("Invalid Tailscale origin");
|
|
425
|
+
remoteOrigin = configured;
|
|
426
|
+
} catch (error: any) {
|
|
427
|
+
if (error.code !== "ENOENT") throw error;
|
|
428
|
+
remoteOrigin = undefined;
|
|
429
|
+
}
|
|
430
|
+
try {
|
|
431
|
+
// Preserve an all-stop made by the older project-local extension.
|
|
432
|
+
try {
|
|
433
|
+
await readFile(join(ctx.cwd, ".pi", "remote-disabled"));
|
|
434
|
+
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
435
|
+
await writeFile(disabledFile, "Pi Remote disabled. Use /remote enable to restart.\n", { mode: 0o600 });
|
|
436
|
+
} catch (error: any) {
|
|
437
|
+
if (error.code !== "ENOENT") throw error;
|
|
438
|
+
}
|
|
439
|
+
await readFile(disabledFile);
|
|
440
|
+
disabled = true;
|
|
441
|
+
ctx.ui.notify("Pi Remote disabled. Use /remote enable to restart.", "info");
|
|
442
|
+
} catch (error: any) {
|
|
443
|
+
if (error.code !== "ENOENT") throw error;
|
|
444
|
+
disabled = false;
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
pi.on("session_tree", async (_event, ctx) => { loadHistory(ctx.sessionManager.getBranch()); });
|
|
449
|
+
pi.on("ui_prompt_start", async (event) => { waiting = { kind: event.kind, title: event.title }; });
|
|
450
|
+
pi.on("ui_prompt_end", async () => { waiting = undefined; });
|
|
451
|
+
pi.on("tool_execution_start", async (event) => {
|
|
452
|
+
messages.push({ role: "tool", id: event.toolCallId, name: event.toolName, args: event.args, state: "running" });
|
|
453
|
+
});
|
|
454
|
+
pi.on("tool_execution_update", async (event) => {
|
|
455
|
+
const item = tool(event.toolCallId);
|
|
456
|
+
if (item) item.output = event.partialResult;
|
|
457
|
+
});
|
|
458
|
+
pi.on("tool_execution_end", async (event) => {
|
|
459
|
+
const item = tool(event.toolCallId);
|
|
460
|
+
if (item) Object.assign(item, { output: event.result, state: event.isError ? "error" : "done" });
|
|
461
|
+
});
|
|
462
|
+
pi.on("message_update", async (event) => { streaming = display(event.message); });
|
|
463
|
+
pi.on("message_end", async (event) => {
|
|
464
|
+
const item = display(event.message);
|
|
465
|
+
if (item) messages.push(item);
|
|
466
|
+
if (event.message.role === "assistant") streaming = undefined;
|
|
467
|
+
});
|
|
468
|
+
pi.on("session_shutdown", async () => {
|
|
469
|
+
sessionActive = false;
|
|
470
|
+
queued = [];
|
|
471
|
+
stopServer();
|
|
472
|
+
});
|
|
473
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
|
|
4
|
+
const execFileAsync = promisify(execFile);
|
|
5
|
+
type Run = (args: string[]) => Promise<string>;
|
|
6
|
+
|
|
7
|
+
async function runTailscale(args: string[]) {
|
|
8
|
+
const { stdout } = await execFileAsync("tailscale", args, { timeout: 10000, maxBuffer: 1024 * 1024 });
|
|
9
|
+
return stdout;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Configure only a private, unoccupied HTTPS listener, or reuse our existing route. */
|
|
13
|
+
export async function prepareTailscale(port: number, run: Run = runTailscale) {
|
|
14
|
+
let status: any;
|
|
15
|
+
try { status = JSON.parse(await run(["status", "--json"])); }
|
|
16
|
+
catch { throw new Error("Cannot read Tailscale status. Install Tailscale and connect this laptop, then try again."); }
|
|
17
|
+
const hostname = typeof status?.Self?.DNSName === "string" ? status.Self.DNSName.replace(/\.$/, "").toLowerCase() : "";
|
|
18
|
+
if (status?.BackendState !== "Running" || !/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.ts\.net$/.test(hostname) || hostname.length > 253) {
|
|
19
|
+
throw new Error("Tailscale is not connected or has no valid MagicDNS hostname. Check Tailscale on the laptop.");
|
|
20
|
+
}
|
|
21
|
+
const authority = `${hostname}:443`;
|
|
22
|
+
const target = `http://127.0.0.1:${port}`;
|
|
23
|
+
const readConfig = async () => {
|
|
24
|
+
const parsed: unknown = JSON.parse(await run(["serve", "status", "--json"]));
|
|
25
|
+
if (parsed !== null && (typeof parsed !== "object" || Array.isArray(parsed))) throw new Error("Invalid Tailscale Serve configuration.");
|
|
26
|
+
return (parsed ?? {}) as { TCP?: Record<string, { HTTPS?: boolean }>; Web?: Record<string, { Handlers?: Record<string, { Proxy?: string }> }>; AllowFunnel?: Record<string, boolean> };
|
|
27
|
+
};
|
|
28
|
+
const isOurs = (config: Awaited<ReturnType<typeof readConfig>>) => config.TCP?.["443"]?.HTTPS === true && config.Web?.[authority]?.Handlers?.["/"]?.Proxy === target && !Object.values(config.AllowFunnel ?? {}).some(Boolean);
|
|
29
|
+
const config = await readConfig();
|
|
30
|
+
if (!isOurs(config)) {
|
|
31
|
+
if (config.TCP?.["443"] || Object.keys(config.Web ?? {}).some((host) => host.endsWith(":443")) || Object.values(config.AllowFunnel ?? {}).some(Boolean)) {
|
|
32
|
+
throw new Error("Tailscale Serve already has another route or Funnel configuration. Check it on the laptop; nothing was changed.");
|
|
33
|
+
}
|
|
34
|
+
try { await run(["serve", "--bg", "--https=443", target]); }
|
|
35
|
+
catch (error: any) {
|
|
36
|
+
const output = `${error?.stdout ?? ""}\n${error?.stderr ?? ""}`;
|
|
37
|
+
const approval = output.match(/https:\/\/login\.tailscale\.com\/f\/serve\?node=[A-Za-z0-9_-]+/)?.[0];
|
|
38
|
+
throw new Error(approval ? `Enable Tailscale Serve at ${approval}, then run /remote pair again.` : "Could not start Tailscale Serve. Check Tailscale and its Serve settings on the laptop.");
|
|
39
|
+
}
|
|
40
|
+
if (!isOurs(await readConfig())) throw new Error("Could not verify the Tailscale Serve route. Check Serve settings on the laptop.");
|
|
41
|
+
}
|
|
42
|
+
return `https://${hostname}`;
|
|
43
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0tarun0709/pi-pocket",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
}
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"description": "A local web interface for a running Pi session",
|
|
9
|
+
"keywords": [
|
|
10
|
+
"pi-package",
|
|
11
|
+
"pi-extension"
|
|
12
|
+
],
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/0Tarun0709/pi-pocket.git"
|
|
16
|
+
},
|
|
17
|
+
"type": "module",
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=24"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"extensions/",
|
|
23
|
+
"web/",
|
|
24
|
+
"README.md",
|
|
25
|
+
"CHANGELOG.md"
|
|
26
|
+
],
|
|
27
|
+
"pi": {
|
|
28
|
+
"extensions": [
|
|
29
|
+
"./extensions/pocket"
|
|
30
|
+
]
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"test": "node --test",
|
|
34
|
+
"typecheck": "tsc --noEmit"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@highlightjs/cdn-assets": "^11.12.0",
|
|
41
|
+
"dompurify": "^3.4.18",
|
|
42
|
+
"marked": "^18.2.1",
|
|
43
|
+
"qrcode": "^1.5.4"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@earendil-works/pi-coding-agent": "^1.6.0",
|
|
47
|
+
"@types/node": "^24.19.2",
|
|
48
|
+
"@types/qrcode": "^1.5.6",
|
|
49
|
+
"jsdom": "^31.0.1",
|
|
50
|
+
"jsqr": "^1.4.0",
|
|
51
|
+
"typescript": "^5.9.3"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/web/index.html
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
6
|
+
<meta name="theme-color" content="#111411">
|
|
7
|
+
<title>Pi Pocket</title>
|
|
8
|
+
<style>
|
|
9
|
+
:root { color-scheme: dark; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #111411; color: #e9ece6; }
|
|
10
|
+
* { box-sizing: border-box; }
|
|
11
|
+
body { margin: 0; }
|
|
12
|
+
button, textarea { font: inherit; }
|
|
13
|
+
button { cursor: pointer; }
|
|
14
|
+
.app { max-width: 680px; height: 100dvh; margin: auto; display: flex; flex-direction: column; background: #171b17; border-inline: 1px solid #292e29; }
|
|
15
|
+
header { padding: max(20px, env(safe-area-inset-top)) 20px 17px; border-bottom: 1px solid #2c322c; display: flex; justify-content: space-between; align-items: center; }
|
|
16
|
+
.brand { display: flex; align-items: center; gap: 12px; }
|
|
17
|
+
.logo { width: 38px; height: 38px; border-radius: 12px; background: #c5e4a4; color: #182117; display: grid; place-items: center; }
|
|
18
|
+
.logo svg { width: 20px; height: 20px; }
|
|
19
|
+
h1, h2, p { margin: 0; }
|
|
20
|
+
h1 { font-size: 16px; letter-spacing: -.02em; }
|
|
21
|
+
.subtitle { margin-top: 4px; font-size: 12px; color: #909c90; }
|
|
22
|
+
.badge { color: #aab5a7; background: #252c25; border: 1px solid #343d33; padding: 7px 10px; border-radius: 20px; font-size: 11px; white-space: nowrap; }
|
|
23
|
+
.badge::before { content: ''; display: inline-block; width: 6px; height: 6px; margin-right: 6px; border-radius: 50%; background: #899687; vertical-align: 1px; }
|
|
24
|
+
html .badge[data-working="true"] { color: #196a37; background: #dcfce7; border-color: #86c99d; }
|
|
25
|
+
.badge[data-working="true"]::before { background: #218347; }
|
|
26
|
+
main { flex: 1; overflow-y: auto; padding: 26px 20px; }
|
|
27
|
+
.session { display: flex; align-items: center; gap: 9px; color: #8d998c; font-size: 11px; font-weight: 600; letter-spacing: .1em; text-transform: uppercase; }
|
|
28
|
+
.session::after { content: ''; height: 1px; background: #303630; flex: 1; }
|
|
29
|
+
.intro { padding: 38px 0 24px; }
|
|
30
|
+
.eyebrow { color: #b8d59e; font-size: 12px; font-weight: 600; margin-bottom: 10px; }
|
|
31
|
+
h2 { font-size: 25px; line-height: 1.2; letter-spacing: -.04em; }
|
|
32
|
+
.intro p:last-child { color: #9aa59a; line-height: 1.55; font-size: 14px; margin-top: 10px; max-width: 380px; }
|
|
33
|
+
.message { margin: 18px 0; }
|
|
34
|
+
.source-label { margin: 18px 0 -12px; font-size: 11px; color: var(--muted, #98a598); text-align: right; }
|
|
35
|
+
.role { color: #98a598; font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; margin-bottom: 9px; }
|
|
36
|
+
.bubble { padding: 15px 16px; border: 1px solid #303830; background: #202620; border-radius: 4px 16px 16px 16px; font-size: 14px; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
37
|
+
.message.user .bubble { background: #303c2e; border-color: #40513b; border-radius: 16px 4px 16px 16px; }
|
|
38
|
+
.tool { margin: 10px 0; border: 1px solid #465046; border-radius: 12px; background: #202620; overflow: hidden; }
|
|
39
|
+
.tool summary { padding: 12px 14px; cursor: pointer; font-size: 13px; overflow-wrap: anywhere; }
|
|
40
|
+
.tool summary strong { font-weight: 700; }
|
|
41
|
+
.tool summary .tool-state { float: right; color: #98a598; font-size: 11px; margin-left: 8px; }
|
|
42
|
+
.tool summary .tool-preview { display: block; margin: 9px 0 0; padding: 0; color: inherit; font: 12px/1.5 monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
43
|
+
.tool[open] summary .tool-preview { display: none; }
|
|
44
|
+
.tool .diff-add { color: #78c88f; } .tool .diff-remove { color: #ed8c91; }
|
|
45
|
+
.hljs-keyword, .hljs-selector-tag, .hljs-literal { color: #c792ea; }
|
|
46
|
+
.hljs-string, .hljs-attr, .hljs-addition { color: #8acb88; }
|
|
47
|
+
.hljs-number, .hljs-symbol, .hljs-variable, .hljs-template-variable { color: #edb777; }
|
|
48
|
+
.hljs-title, .hljs-function, .hljs-attribute { color: #87baf2; }
|
|
49
|
+
.hljs-comment, .hljs-quote { color: #929ba5; font-style: italic; }
|
|
50
|
+
html[data-theme="light"] .hljs-keyword, html[data-theme="light"] .hljs-selector-tag, html[data-theme="light"] .hljs-literal { color: #803ea0; }
|
|
51
|
+
html[data-theme="light"] .hljs-string, html[data-theme="light"] .hljs-attr { color: #287c35; }
|
|
52
|
+
html[data-theme="light"] .hljs-number, html[data-theme="light"] .hljs-symbol { color: #a24e00; }
|
|
53
|
+
html[data-theme="light"] .hljs-title, html[data-theme="light"] .hljs-function { color: #215f9e; }
|
|
54
|
+
html[data-theme="light"] .tool .diff-add { color: #187338; } html[data-theme="light"] .tool .diff-remove { color: #b62c36; }
|
|
55
|
+
.tool-body { padding: 0 14px 14px; font-size: 12px; }
|
|
56
|
+
.tool-body h3 { font-size: 11px; text-transform: uppercase; color: #98a598; margin: 12px 0 6px; }
|
|
57
|
+
.tool-body pre { margin: 0; padding: 10px; background: #151a15; border-radius: 8px; white-space: pre-wrap; overflow-wrap: anywhere; overflow-x: auto; }
|
|
58
|
+
html:not([data-theme="forest"]) .tool { background: var(--panel); border-color: var(--border); }
|
|
59
|
+
html:not([data-theme="forest"]) .tool-body pre { background: var(--code); }
|
|
60
|
+
html:not([data-theme="forest"]) .tool-body h3 { color: var(--muted); }
|
|
61
|
+
.markdown { white-space: normal; }
|
|
62
|
+
.markdown > :first-child { margin-top: 0; }
|
|
63
|
+
.markdown > :last-child { margin-bottom: 0; }
|
|
64
|
+
.markdown p, .markdown ul, .markdown ol, .markdown blockquote { margin: .7em 0; }
|
|
65
|
+
.markdown h1, .markdown h2, .markdown h3, .markdown h4 { margin: 1em 0 .5em; line-height: 1.3; }
|
|
66
|
+
.markdown h1 { font-size: 1.5em; } .markdown h2 { font-size: 1.3em; } .markdown h3 { font-size: 1.15em; }
|
|
67
|
+
.markdown a { color: #c5e4a4; }
|
|
68
|
+
.markdown code { background: #303830; border-radius: 4px; padding: .15em .3em; font-size: .9em; }
|
|
69
|
+
.markdown pre { overflow-x: auto; background: #151a15; padding: 12px; border-radius: 8px; }
|
|
70
|
+
.markdown pre code { padding: 0; background: none; }
|
|
71
|
+
.markdown blockquote { border-left: 3px solid #718a69; padding-left: 12px; color: #b8c4b5; }
|
|
72
|
+
.markdown .table-scroll { overflow-x: auto; }
|
|
73
|
+
.markdown table { border-collapse: collapse; width: 100%; }
|
|
74
|
+
.markdown th, .markdown td { border: 1px solid #465046; padding: 6px 9px; text-align: left; }
|
|
75
|
+
.markdown input[type="checkbox"] { margin-right: .4em; }
|
|
76
|
+
.example { margin-top: 28px; padding: 13px 14px; border: 1px dashed #394339; border-radius: 12px; color: #a8b4a5; font-size: 12px; line-height: 1.5; }
|
|
77
|
+
footer { padding: 12px 16px max(16px, env(safe-area-inset-bottom)); border-top: 1px solid #2c322c; }
|
|
78
|
+
.composer { display: flex; align-items: end; gap: 10px; padding: 10px; background: #222822; border: 1px solid #394339; border-radius: 16px; }
|
|
79
|
+
textarea { flex: 1; resize: none; min-height: 42px; max-height: 120px; padding: 10px 4px; background: transparent; color: #ecf1e9; border: 0; outline: 0; line-height: 1.4; }
|
|
80
|
+
textarea::placeholder { color: #879387; }
|
|
81
|
+
button { width: 42px; height: 42px; flex: none; border: 0; border-radius: 11px; background: #c5e4a4; color: #192218; font-size: 21px; }
|
|
82
|
+
button:focus-visible, textarea:focus-visible { outline: 2px solid #c5e4a4; outline-offset: 2px; }
|
|
83
|
+
.footnote { text-align: center; color: #899588; font-size: 11px; margin-top: 10px; }
|
|
84
|
+
.header-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; }
|
|
85
|
+
.sessions { position: relative; }
|
|
86
|
+
.sessions summary { list-style: none; cursor: pointer; font-size: 12px; padding: 7px 9px; border: 1px solid #465046; border-radius: 8px; }
|
|
87
|
+
.sessions summary::-webkit-details-marker { display: none; }
|
|
88
|
+
.sessions summary:focus-visible { outline: 2px solid #c5e4a4; outline-offset: 2px; }
|
|
89
|
+
.sessions-panel { position: absolute; z-index: 2; right: 0; top: calc(100% + 8px); width: 240px; padding: 16px; background: #252c25; border: 1px solid #465046; border-radius: 12px; box-shadow: 0 8px 24px #0004; font-size: 13px; }
|
|
90
|
+
.sessions-panel p { margin-top: 8px; color: #a8b4a5; line-height: 1.5; overflow-wrap: anywhere; }
|
|
91
|
+
.sessions-panel button { display: block; width: 100%; height: auto; margin-top: 10px; padding: 9px; border: 1px solid #657361; border-radius: 8px; background: transparent; color: inherit; font-size: 12px; text-align: left; }
|
|
92
|
+
html .sessions-panel button.danger { display: flex; align-items: center; gap: 8px; background: #c83232; color: #fff; border-color: #c83232; font-weight: 700; }
|
|
93
|
+
html .sessions-panel button.danger:hover { background: #a92323; border-color: #a92323; }
|
|
94
|
+
.sessions-panel button.danger svg { flex: none; }
|
|
95
|
+
html:not([data-theme="forest"]) .sessions summary, html:not([data-theme="forest"]) .sessions-panel { background: var(--panel); border-color: var(--border); color: var(--text); }
|
|
96
|
+
html:not([data-theme="forest"]) .sessions-panel p { color: var(--muted); }
|
|
97
|
+
select { font: inherit; font-size: 12px; color: inherit; background: #252c25; border: 1px solid #465046; border-radius: 8px; padding: 7px; max-width: 110px; }
|
|
98
|
+
select:focus-visible { outline: 2px solid #c5e4a4; outline-offset: 2px; }
|
|
99
|
+
html:not([data-theme="forest"]) { --bg: #101114; --surface: #191b20; --panel: #24272e; --user: #303845; --border: #454b55; --text: #eef0f4; --muted: #b2b8c2; --accent: #a9c7ff; --accent-text: #111a29; --code: #121419; background: var(--bg); color: var(--text); }
|
|
100
|
+
html[data-theme="light"] { color-scheme: light; --bg: #e9edf3; --surface: #ffffff; --panel: #f1f3f7; --user: #e2ebfa; --border: #b8c2d1; --text: #192332; --muted: #526173; --accent: #315ca6; --accent-text: #ffffff; --code: #e5eaf1; }
|
|
101
|
+
html:not([data-theme="forest"]) .app { background: var(--surface); border-color: var(--border); }
|
|
102
|
+
html:not([data-theme="forest"]) header, html:not([data-theme="forest"]) footer { border-color: var(--border); }
|
|
103
|
+
html:not([data-theme="forest"]) .subtitle, html:not([data-theme="forest"]) .session, html:not([data-theme="forest"]) .role, html:not([data-theme="forest"]) .footnote, html:not([data-theme="forest"]) .example, html:not([data-theme="forest"]) .markdown blockquote { color: var(--muted); }
|
|
104
|
+
html:not([data-theme="forest"]) .badge, html:not([data-theme="forest"]) select, html:not([data-theme="forest"]) .composer, html:not([data-theme="forest"]) .bubble { background: var(--panel); color: var(--text); border-color: var(--border); }
|
|
105
|
+
html:not([data-theme="forest"]) .message.user .bubble { background: var(--user); border-color: var(--border); }
|
|
106
|
+
html:not([data-theme="forest"]) .logo, html:not([data-theme="forest"]) button { background: var(--accent); color: var(--accent-text); }
|
|
107
|
+
html:not([data-theme="forest"]) .markdown a { color: var(--accent); }
|
|
108
|
+
html:not([data-theme="forest"]) .markdown code { background: var(--panel); }
|
|
109
|
+
html:not([data-theme="forest"]) .markdown pre { background: var(--code); }
|
|
110
|
+
html:not([data-theme="forest"]) .markdown pre code { background: none; }
|
|
111
|
+
html:not([data-theme="forest"]) .markdown th, html:not([data-theme="forest"]) .markdown td, html:not([data-theme="forest"]) .example { border-color: var(--border); }
|
|
112
|
+
html:not([data-theme="forest"]) textarea { color: var(--text); }
|
|
113
|
+
html:not([data-theme="forest"]) textarea::placeholder { color: var(--muted); }
|
|
114
|
+
html:not([data-theme="forest"]) :is(button, textarea, select):focus-visible { outline-color: var(--accent); }
|
|
115
|
+
@media (max-width: 380px) { .subtitle { display: none; } }
|
|
116
|
+
</style>
|
|
117
|
+
</head>
|
|
118
|
+
<body>
|
|
119
|
+
<div class="app">
|
|
120
|
+
<header>
|
|
121
|
+
<div class="brand"><div class="logo" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" fill="currentColor"><path d="M0 0 H300 V200 H200 V100 H0 Z"/><path d="M0 100 H100 V200 H200 V300 H100 V400 H0 Z"/><rect x="300" y="200" width="100" height="200"/></svg></div><div><h1>Pi Pocket</h1><p class="subtitle">Your agent, wherever you are</p></div></div>
|
|
122
|
+
<div class="header-actions">
|
|
123
|
+
<span class="badge" id="status">Connecting</span>
|
|
124
|
+
<details class="sessions">
|
|
125
|
+
<summary>Sessions</summary>
|
|
126
|
+
<div class="sessions-panel"><strong>Session actions</strong><p id="browser-label">This browser: checking…</p><button type="button" id="disconnect-tailscale">Turn off Tailscale access</button><button type="button" class="danger" id="stop-all"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><rect x="9" y="9" width="6" height="6" rx="1"/></svg>Stop all & disconnect</button><p>Session switching is not connected yet.</p></div>
|
|
127
|
+
</details>
|
|
128
|
+
<select id="theme" aria-label="Choose color theme">
|
|
129
|
+
<option value="graphite">Graphite</option>
|
|
130
|
+
<option value="light">Light</option>
|
|
131
|
+
<option value="forest">Forest</option>
|
|
132
|
+
</select>
|
|
133
|
+
</div>
|
|
134
|
+
</header>
|
|
135
|
+
<main id="conversation" aria-label="Conversation">
|
|
136
|
+
<div class="session">Current session</div>
|
|
137
|
+
<div id="messages"></div>
|
|
138
|
+
<div class="example" id="notice" role="status">Connecting to Pi…</div>
|
|
139
|
+
</main>
|
|
140
|
+
<footer>
|
|
141
|
+
<form class="composer" id="composer"><textarea id="prompt" rows="1" aria-label="Message Pi" placeholder="Message Pi…"></textarea><button type="submit" aria-label="Send message">↑</button></form>
|
|
142
|
+
<p class="footnote">Use the stop button to interrupt Pi while it is working.</p>
|
|
143
|
+
</footer>
|
|
144
|
+
</div>
|
|
145
|
+
<script src="/marked.js"></script>
|
|
146
|
+
<script src="/purify.js"></script>
|
|
147
|
+
<script src="/highlight.js"></script>
|
|
148
|
+
<script>
|
|
149
|
+
const theme = document.querySelector('#theme');
|
|
150
|
+
const savedTheme = document.cookie.split('; ').find(row => row.startsWith('pi-remote-theme='))?.split('=')[1];
|
|
151
|
+
if ([...theme.options].some(option => option.value === savedTheme)) theme.value = savedTheme;
|
|
152
|
+
document.documentElement.dataset.theme = theme.value;
|
|
153
|
+
theme.addEventListener('change', () => {
|
|
154
|
+
document.documentElement.dataset.theme = theme.value;
|
|
155
|
+
document.cookie = `pi-remote-theme=${theme.value}; Max-Age=31536000; Path=/; SameSite=Strict`;
|
|
156
|
+
});
|
|
157
|
+
const form = document.querySelector('#composer');
|
|
158
|
+
const prompt = document.querySelector('#prompt');
|
|
159
|
+
const conversation = document.querySelector('#conversation');
|
|
160
|
+
const messages = document.querySelector('#messages');
|
|
161
|
+
const status = document.querySelector('#status');
|
|
162
|
+
const notice = document.querySelector('#notice');
|
|
163
|
+
const button = form.querySelector('button');
|
|
164
|
+
let lastMessages = '';
|
|
165
|
+
let stoppedAll = false;
|
|
166
|
+
let busy = false;
|
|
167
|
+
let actionNotice = '';
|
|
168
|
+
function updateSendButton() {
|
|
169
|
+
button.setAttribute('aria-label', busy ? 'Stop execution' : 'Send message');
|
|
170
|
+
button.textContent = busy ? '■' : '↑';
|
|
171
|
+
}
|
|
172
|
+
async function stop(all) {
|
|
173
|
+
if (all && !confirm('Stop Pi, discard queued web prompts, and disable Pi Pocket? Re-enable it from the laptop with /remote enable.')) return;
|
|
174
|
+
try {
|
|
175
|
+
const response = await fetch(all ? '/api/stop-all' : '/api/stop', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
|
176
|
+
if (!response.ok) throw new Error(await response.text());
|
|
177
|
+
if (all) {
|
|
178
|
+
stoppedAll = true;
|
|
179
|
+
status.textContent = 'Disabled';
|
|
180
|
+
status.dataset.working = 'false';
|
|
181
|
+
notice.hidden = false;
|
|
182
|
+
notice.textContent = 'Pi Pocket is disabled. Use /remote enable in the laptop terminal to enable it.';
|
|
183
|
+
button.disabled = true;
|
|
184
|
+
}
|
|
185
|
+
} catch (error) {
|
|
186
|
+
notice.hidden = false;
|
|
187
|
+
notice.textContent = `Could not complete the stop request: ${error.message}`;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
document.querySelector('#stop-all').addEventListener('click', () => stop(true));
|
|
191
|
+
document.querySelector('#disconnect-tailscale').addEventListener('click', async (event) => {
|
|
192
|
+
if (!confirm('Turn off Pi Pocket’s Tailscale connection for all devices? Pi will keep running on the laptop.')) return;
|
|
193
|
+
const control = event.currentTarget;
|
|
194
|
+
control.disabled = true;
|
|
195
|
+
actionNotice = 'Turning off Tailscale access…';
|
|
196
|
+
notice.hidden = false;
|
|
197
|
+
notice.textContent = actionNotice;
|
|
198
|
+
try {
|
|
199
|
+
const response = await fetch('/api/disconnect-tailscale', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
|
200
|
+
if (!response.ok) throw new Error(await response.text());
|
|
201
|
+
actionNotice = 'Tailscale access is off. Pi is still running on the laptop.';
|
|
202
|
+
notice.textContent = actionNotice;
|
|
203
|
+
if (location.protocol === 'https:') {
|
|
204
|
+
stoppedAll = true;
|
|
205
|
+
status.textContent = 'Disconnected';
|
|
206
|
+
status.dataset.working = 'false';
|
|
207
|
+
button.disabled = true;
|
|
208
|
+
}
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (error instanceof TypeError && location.protocol === 'https:') {
|
|
211
|
+
stoppedAll = true;
|
|
212
|
+
status.textContent = 'Connection lost';
|
|
213
|
+
status.dataset.working = 'false';
|
|
214
|
+
button.disabled = true;
|
|
215
|
+
actionNotice = 'Connection lost while turning off access. Check Tailscale Serve on the laptop to confirm.';
|
|
216
|
+
notice.textContent = actionNotice;
|
|
217
|
+
} else {
|
|
218
|
+
actionNotice = `Could not turn off Tailscale access: ${error.message}`;
|
|
219
|
+
notice.textContent = actionNotice;
|
|
220
|
+
control.disabled = false;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
const openTools = new Set();
|
|
225
|
+
function toolText(output) {
|
|
226
|
+
const content = Array.isArray(output) ? output : output?.content;
|
|
227
|
+
if (typeof content === 'string') return content;
|
|
228
|
+
if (Array.isArray(content)) return content.map(part => part.type === 'text' ? part.text : `[${part.type || 'attachment'}]`).join('\n');
|
|
229
|
+
return typeof output === 'string' ? output : '';
|
|
230
|
+
}
|
|
231
|
+
function toolTitle(item) {
|
|
232
|
+
const args = item.args || {};
|
|
233
|
+
const path = args.file_path ?? args.path ?? '';
|
|
234
|
+
if (item.name === 'bash' || item.name === 'powershell') return `${item.name === 'bash' ? '$' : '>'} ${args.command || '…'}`;
|
|
235
|
+
if (item.name === 'grep') return `grep /${args.pattern || ''}/ in ${path || '.'}`;
|
|
236
|
+
if (item.name === 'find') return `find ${args.pattern || ''} in ${path || '.'}`;
|
|
237
|
+
return `${item.name}${path ? ` ${path}` : ''}`;
|
|
238
|
+
}
|
|
239
|
+
function codeBlock(text, path, diff = false) {
|
|
240
|
+
const pre = document.createElement('pre');
|
|
241
|
+
const code = document.createElement('code');
|
|
242
|
+
code.textContent = text;
|
|
243
|
+
const extension = path?.split('.').pop()?.toLowerCase();
|
|
244
|
+
const aliases = { js: 'javascript', ts: 'typescript', tsx: 'typescript', jsx: 'javascript', py: 'python', sh: 'bash', yml: 'yaml', clj: 'clojure', html: 'xml' };
|
|
245
|
+
const language = aliases[extension] || extension;
|
|
246
|
+
if (!diff && language && hljs.getLanguage(language)) {
|
|
247
|
+
code.className = `language-${language}`;
|
|
248
|
+
hljs.highlightElement(code);
|
|
249
|
+
}
|
|
250
|
+
if (diff) {
|
|
251
|
+
code.replaceChildren(...text.split('\n').flatMap((line, index) => {
|
|
252
|
+
const span = document.createElement('span');
|
|
253
|
+
span.className = /^\s*\+/.test(line) ? 'diff-add' : /^\s*-/.test(line) ? 'diff-remove' : '';
|
|
254
|
+
span.textContent = line;
|
|
255
|
+
return index ? [document.createTextNode('\n'), span] : [span];
|
|
256
|
+
}));
|
|
257
|
+
}
|
|
258
|
+
pre.append(code);
|
|
259
|
+
return pre;
|
|
260
|
+
}
|
|
261
|
+
function renderTool(item) {
|
|
262
|
+
const details = document.createElement('details');
|
|
263
|
+
details.className = 'tool';
|
|
264
|
+
details.open = openTools.has(item.id);
|
|
265
|
+
details.addEventListener('toggle', () => {
|
|
266
|
+
if (details.open) openTools.add(item.id); else openTools.delete(item.id);
|
|
267
|
+
});
|
|
268
|
+
const args = item.args || {};
|
|
269
|
+
const path = args.file_path ?? args.path;
|
|
270
|
+
const output = toolText(item.output);
|
|
271
|
+
const diff = item.name === 'edit' && typeof item.output?.details?.diff === 'string' ? item.output.details.diff : '';
|
|
272
|
+
const content = diff || (item.name === 'write' && item.state !== 'error' ? args.content : output) || '';
|
|
273
|
+
const summary = document.createElement('summary');
|
|
274
|
+
const title = document.createElement('strong');
|
|
275
|
+
title.textContent = toolTitle(item);
|
|
276
|
+
const state = document.createElement('span');
|
|
277
|
+
state.className = 'tool-state';
|
|
278
|
+
state.textContent = item.state === 'unknown' ? 'result unavailable' : item.state;
|
|
279
|
+
summary.append(title, state);
|
|
280
|
+
if (content && item.name !== 'read') {
|
|
281
|
+
const lines = content.trimEnd().split('\n');
|
|
282
|
+
const limit = item.name === 'bash' || item.name === 'powershell' ? 5 : 10;
|
|
283
|
+
const previewText = (item.name === 'bash' || item.name === 'powershell' ? lines.slice(-limit) : lines.slice(0, limit)).join('\n') + (lines.length > limit ? `\n… ${lines.length - limit} more lines` : '');
|
|
284
|
+
const preview = codeBlock(previewText, path, Boolean(diff));
|
|
285
|
+
preview.className = 'tool-preview';
|
|
286
|
+
summary.append(preview);
|
|
287
|
+
}
|
|
288
|
+
const body = document.createElement('div');
|
|
289
|
+
body.className = 'tool-body';
|
|
290
|
+
if (content) body.append(codeBlock(content, path, Boolean(diff)));
|
|
291
|
+
if (item.state === 'error' && diff && output) body.append(codeBlock(output));
|
|
292
|
+
if (!content && item.args && !['read', 'bash', 'powershell', 'write', 'edit', 'grep', 'find', 'ls'].includes(item.name)) body.append(codeBlock(JSON.stringify(item.args, null, 2)));
|
|
293
|
+
details.append(summary, body);
|
|
294
|
+
return details;
|
|
295
|
+
}
|
|
296
|
+
async function refresh() {
|
|
297
|
+
if (stoppedAll) return;
|
|
298
|
+
try {
|
|
299
|
+
const response = await fetch('/api/session', { cache: 'no-store' });
|
|
300
|
+
if (response.status === 401) { location.replace('/pair'); return; }
|
|
301
|
+
if (!response.ok) throw new Error('Disconnected');
|
|
302
|
+
const session = await response.json();
|
|
303
|
+
busy = session.busy;
|
|
304
|
+
updateSendButton();
|
|
305
|
+
status.textContent = session.waiting ? 'Waiting for input' : session.busy ? 'Working' : 'Connected';
|
|
306
|
+
status.dataset.working = String(session.busy && !session.waiting);
|
|
307
|
+
if (session.local) document.querySelector('#browser-label').textContent = 'This browser: local access';
|
|
308
|
+
else if (session.browser) document.querySelector('#browser-label').textContent = `This browser: ${session.browser.label} · ${session.browser.id}`;
|
|
309
|
+
document.querySelector('.footnote').textContent = session.queued ? `${session.queued} web prompt${session.queued === 1 ? '' : 's'} queued.` : 'Use the stop button to interrupt Pi while it is working.';
|
|
310
|
+
notice.hidden = !session.waiting && !actionNotice;
|
|
311
|
+
if (session.waiting) notice.textContent = `Pi is waiting for ${session.waiting.title || session.waiting.kind}. Answer it in the laptop terminal; remote answers are not supported yet.`;
|
|
312
|
+
else if (actionNotice) notice.textContent = actionNotice;
|
|
313
|
+
const serialized = JSON.stringify(session.messages);
|
|
314
|
+
if (serialized === lastMessages) return;
|
|
315
|
+
lastMessages = serialized;
|
|
316
|
+
const nearBottom = conversation.scrollHeight - conversation.scrollTop - conversation.clientHeight < 100;
|
|
317
|
+
messages.replaceChildren(...session.messages.map((item) => {
|
|
318
|
+
if (item.role === 'tool') return renderTool(item);
|
|
319
|
+
if (item.role === 'source') {
|
|
320
|
+
const source = document.createElement('div');
|
|
321
|
+
source.className = 'source-label';
|
|
322
|
+
source.textContent = item.via === 'tailscale' ? 'Pi Pocket · Tailscale address' : 'Pi Pocket · local address';
|
|
323
|
+
return source;
|
|
324
|
+
}
|
|
325
|
+
const message = document.createElement('div');
|
|
326
|
+
message.className = `message ${item.role === 'user' ? 'user' : ''}`;
|
|
327
|
+
const role = document.createElement('div');
|
|
328
|
+
role.className = 'role';
|
|
329
|
+
role.textContent = item.role === 'user' ? 'You' : 'Pi';
|
|
330
|
+
const bubble = document.createElement('div');
|
|
331
|
+
bubble.className = 'bubble';
|
|
332
|
+
if (item.role === 'assistant') {
|
|
333
|
+
bubble.classList.add('markdown');
|
|
334
|
+
bubble.innerHTML = DOMPurify.sanitize(marked.parse(item.text), {
|
|
335
|
+
USE_PROFILES: { html: true },
|
|
336
|
+
FORBID_TAGS: ['img', 'style', 'form'],
|
|
337
|
+
});
|
|
338
|
+
for (const code of bubble.querySelectorAll('pre code[class*="language-"]')) {
|
|
339
|
+
if (hljs.getLanguage(code.className.match(/language-([^\s]+)/)?.[1])) hljs.highlightElement(code);
|
|
340
|
+
}
|
|
341
|
+
for (const table of bubble.querySelectorAll('table')) {
|
|
342
|
+
const wrapper = document.createElement('div');
|
|
343
|
+
wrapper.className = 'table-scroll';
|
|
344
|
+
table.replaceWith(wrapper);
|
|
345
|
+
wrapper.append(table);
|
|
346
|
+
}
|
|
347
|
+
} else {
|
|
348
|
+
bubble.textContent = item.text;
|
|
349
|
+
}
|
|
350
|
+
message.append(role, bubble);
|
|
351
|
+
return message;
|
|
352
|
+
}));
|
|
353
|
+
if (nearBottom) conversation.scrollTop = conversation.scrollHeight;
|
|
354
|
+
} catch {
|
|
355
|
+
status.textContent = 'Disconnected';
|
|
356
|
+
status.dataset.working = 'false';
|
|
357
|
+
notice.hidden = false;
|
|
358
|
+
notice.textContent = 'Cannot connect to Pi. Open the address shown by the extension, not this HTML file directly.';
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
form.addEventListener('submit', async (event) => {
|
|
362
|
+
event.preventDefault();
|
|
363
|
+
if (busy) { await stop(false); return; }
|
|
364
|
+
const text = prompt.value.trim();
|
|
365
|
+
if (!text) return;
|
|
366
|
+
button.disabled = true;
|
|
367
|
+
try {
|
|
368
|
+
const response = await fetch('/api/prompt', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) });
|
|
369
|
+
if (!response.ok) throw new Error('Send failed');
|
|
370
|
+
if (prompt.value.trim() === text) prompt.value = '';
|
|
371
|
+
await refresh();
|
|
372
|
+
} catch {
|
|
373
|
+
notice.hidden = false;
|
|
374
|
+
notice.textContent = 'Could not send. Your message is still in the composer.';
|
|
375
|
+
} finally { button.disabled = false; }
|
|
376
|
+
});
|
|
377
|
+
refresh();
|
|
378
|
+
setInterval(refresh, 1500);
|
|
379
|
+
</script>
|
|
380
|
+
</body>
|
|
381
|
+
</html>
|
package/web/pair.html
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
6
|
+
<meta name="referrer" content="no-referrer">
|
|
7
|
+
<meta name="theme-color" content="#191b20">
|
|
8
|
+
<title>Pair browser · Pi Pocket</title>
|
|
9
|
+
<style>
|
|
10
|
+
:root { color-scheme: dark; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #101114; color: #eef0f4; }
|
|
11
|
+
* { box-sizing: border-box; }
|
|
12
|
+
body { min-height: 100dvh; margin: 0; display: grid; place-items: center; padding: 24px; }
|
|
13
|
+
main { width: min(100%, 420px); padding: 28px; border: 1px solid #454b55; border-radius: 18px; background: #191b20; }
|
|
14
|
+
.brand { display: flex; align-items: center; gap: 12px; font-size: 14px; font-weight: 700; }
|
|
15
|
+
.logo { width: 38px; height: 38px; display: grid; place-items: center; border-radius: 12px; background: #a9c7ff; color: #111a29; }
|
|
16
|
+
.logo svg { width: 20px; height: 20px; }
|
|
17
|
+
h1 { margin: 28px 0 10px; font-size: 24px; letter-spacing: -.03em; }
|
|
18
|
+
p { margin: 0; color: #b2b8c2; line-height: 1.55; font-size: 14px; }
|
|
19
|
+
form { margin-top: 26px; }
|
|
20
|
+
label { display: block; margin-bottom: 8px; font-size: 13px; font-weight: 600; }
|
|
21
|
+
input, button { width: 100%; font: inherit; border-radius: 10px; }
|
|
22
|
+
input { padding: 13px; color: #eef0f4; background: #24272e; border: 1px solid #454b55; font-size: 16px; }
|
|
23
|
+
input:focus-visible, button:focus-visible { outline: 2px solid #a9c7ff; outline-offset: 3px; }
|
|
24
|
+
button { margin-top: 12px; padding: 13px; border: 0; background: #a9c7ff; color: #111a29; font-weight: 700; cursor: pointer; }
|
|
25
|
+
button:disabled { opacity: .6; cursor: wait; }
|
|
26
|
+
#status { min-height: 1.5em; margin-top: 14px; color: #f4aaaa; }
|
|
27
|
+
.footnote { margin-top: 20px; font-size: 12px; }
|
|
28
|
+
</style>
|
|
29
|
+
</head>
|
|
30
|
+
<body>
|
|
31
|
+
<main>
|
|
32
|
+
<div class="brand"><span class="logo" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" fill="currentColor"><path d="M0 0 H300 V200 H200 V100 H0 Z"/><path d="M0 100 H100 V200 H200 V300 H100 V400 H0 Z"/><rect x="300" y="200" width="100" height="200"/></svg></span>Pi Pocket</div>
|
|
33
|
+
<h1>Pair this browser</h1>
|
|
34
|
+
<p>On your laptop, run <strong>/remote pair</strong> in Pi to pair your phone. For laptop-only access, open <strong>http://127.0.0.1:18790</strong> on the laptop. Scan the QR code or enter the code below.</p>
|
|
35
|
+
<form id="pair-form">
|
|
36
|
+
<label for="code">Pairing code</label>
|
|
37
|
+
<input id="code" name="code" required autocomplete="off" autocapitalize="off" spellcheck="false" maxlength="32">
|
|
38
|
+
<button type="submit">Pair browser</button>
|
|
39
|
+
</form>
|
|
40
|
+
<p id="status" role="status" aria-live="polite"></p>
|
|
41
|
+
<p class="footnote">The code expires after two minutes and works once. Keep it private.</p>
|
|
42
|
+
</main>
|
|
43
|
+
<script>
|
|
44
|
+
const form = document.querySelector('#pair-form');
|
|
45
|
+
const input = document.querySelector('#code');
|
|
46
|
+
const status = document.querySelector('#status');
|
|
47
|
+
const button = form.querySelector('button');
|
|
48
|
+
const fragment = new URLSearchParams(location.hash.slice(1));
|
|
49
|
+
const scanned = fragment.get('pair');
|
|
50
|
+
if (location.hash) history.replaceState(null, '', location.pathname);
|
|
51
|
+
async function pair(code) {
|
|
52
|
+
button.disabled = true;
|
|
53
|
+
status.textContent = 'Pairing…';
|
|
54
|
+
try {
|
|
55
|
+
const response = await fetch('/api/pair', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: code.trim() }) });
|
|
56
|
+
if (!response.ok) throw new Error(response.status === 401 ? 'This code is invalid or expired. Run /remote pair for a new one.' : 'Could not pair. Run /remote pair for a new code and try again.');
|
|
57
|
+
location.replace('/');
|
|
58
|
+
} catch (error) {
|
|
59
|
+
status.textContent = error.message || 'Could not connect. Check Tailscale and try again.';
|
|
60
|
+
button.disabled = false;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
form.addEventListener('submit', event => { event.preventDefault(); void pair(input.value); });
|
|
64
|
+
if (scanned) void pair(scanned);
|
|
65
|
+
</script>
|
|
66
|
+
</body>
|
|
67
|
+
</html>
|