pi-ahp 0.0.0 → 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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +97 -28
  3. package/dist/bin/cli.js +54 -0
  4. package/dist/bin/tunnel.js +115 -0
  5. package/dist/channels/chat.js +105 -0
  6. package/dist/channels/root.js +30 -0
  7. package/dist/channels/session.js +89 -0
  8. package/dist/channels/terminal.js +9 -0
  9. package/dist/core/channels.js +87 -0
  10. package/dist/core/client-workarounds.js +304 -0
  11. package/dist/core/connection.js +24 -0
  12. package/dist/core/host.js +644 -0
  13. package/dist/core/sequencer.js +64 -0
  14. package/dist/core/state-store.js +118 -0
  15. package/dist/core/uri.js +22 -0
  16. package/dist/host/direct-settings.js +93 -0
  17. package/dist/host/pi-host.js +141 -0
  18. package/dist/host/serve.js +47 -0
  19. package/dist/host/terminal-service.js +298 -0
  20. package/dist/pi/activity.js +158 -0
  21. package/dist/pi/chat-driver.js +344 -0
  22. package/dist/pi/completions.js +131 -0
  23. package/dist/pi/delete-session.js +44 -0
  24. package/dist/pi/event-mapper.js +535 -0
  25. package/dist/pi/history.js +220 -0
  26. package/dist/pi/in-process-backend.js +108 -0
  27. package/dist/pi/message-input.js +145 -0
  28. package/dist/pi/models.js +103 -0
  29. package/dist/pi/project-trust.js +40 -0
  30. package/dist/pi/provider.js +2 -0
  31. package/dist/pi/resource-paths.js +76 -0
  32. package/dist/pi/resource-service.js +290 -0
  33. package/dist/pi/resource-watch-policy.js +29 -0
  34. package/dist/pi/resource-watch.js +310 -0
  35. package/dist/pi/session-catalogue.js +283 -0
  36. package/dist/pi/session-config.js +63 -0
  37. package/dist/pi/session-history.js +51 -0
  38. package/dist/pi/session-hydrator.js +144 -0
  39. package/dist/pi/session-registry.js +635 -0
  40. package/dist/pi/session-title.js +15 -0
  41. package/dist/pi/turn-paging.js +70 -0
  42. package/dist/protocol/errors.js +35 -0
  43. package/dist/protocol/jsonrpc.js +46 -0
  44. package/dist/protocol/version.js +32 -0
  45. package/dist/transport/websocket.js +101 -0
  46. package/dist/tunnel/devtunnel.js +127 -0
  47. package/dist/tunnel/vscode.js +31 -0
  48. package/package.json +66 -8
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bang Lee
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,45 +1,114 @@
1
1
  # pi-ahp
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ [![CI](https://github.com/Qusic/pi-ahp/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/Qusic/pi-ahp/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/pi-ahp)](https://www.npmjs.com/package/pi-ahp)
5
+ [![pi](https://img.shields.io/npm/dependency-version/pi-ahp/@earendil-works/pi-coding-agent?label=pi)](https://github.com/earendil-works/pi)
6
+ [![AHP](https://img.shields.io/npm/dependency-version/pi-ahp/@microsoft/agent-host-protocol?label=AHP)](https://github.com/microsoft/agent-host-protocol)
7
+ [![License](https://img.shields.io/npm/l/pi-ahp)](LICENSE)
4
8
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
9
+ `pi-ahp` is an [Agent Host Protocol](https://github.com/microsoft/agent-host-protocol) host for the [pi coding agent](https://github.com/earendil-works/pi).
6
10
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
11
+ It embeds pi and makes its sessions available to AHP clients over WebSocket. Interoperability is primarily tested with [Agent Host support in Visual Studio Code](https://code.visualstudio.com/docs/agents/concepts/agent-host) and [Agent Console for iPhone and iPad](https://qusic.github.io/agent-console/), but the host is not limited to either client.
8
12
 
9
- ## Purpose
13
+ The project is under active development; expect rough edges and occasional instability. Contributions are welcome.
10
14
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `pi-ahp`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
15
+ ## Requirements
15
16
 
16
- ## What is OIDC Trusted Publishing?
17
+ - Node.js 24 or later
18
+ - At least one model provider configured for pi
17
19
 
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
20
+ ## Usage
19
21
 
20
- ## Setup Instructions
22
+ ```sh
23
+ npm install --global pi-ahp
24
+ ```
21
25
 
22
- To properly configure OIDC trusted publishing for this package:
26
+ `pi-ahp` starts a direct WebSocket listener and prints its connection URL:
23
27
 
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
+ ```sh
29
+ pi-ahp
30
+ ```
28
31
 
29
- ## DO NOT USE THIS PACKAGE
32
+ On first run, it creates `~/.pi/ahp/settings.json` with a free port and a random token, for example:
30
33
 
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
34
+ ```json
35
+ {
36
+ "host": "127.0.0.1",
37
+ "port": 32145,
38
+ "token": "<generated token>"
39
+ }
40
+ ```
36
41
 
37
- ## More Information
42
+ The token is optional and may be set to `null`. The host and port can also be overridden for one run:
38
43
 
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
44
+ ```sh
45
+ pi-ahp --host 127.0.0.1 --port 31546
46
+ ```
42
47
 
43
- ---
48
+ Enter the printed URL in any AHP client. The direct listener is bring-your-own-network: reach it through Tailscale, SSH port forwarding, a reverse proxy, or any other network you manage. Keep the connection token enabled whenever the listener is reachable beyond localhost.
44
49
 
45
- **Maintained for OIDC setup purposes only**
50
+ `pi-ahp-tunnel` instead creates or reuses a Microsoft Dev Tunnel for clients that support it, including VS Code and Agent Console. It requires the [`devtunnel` CLI](https://aka.ms/devtunnels/download) and does not use the direct-listener settings:
51
+
52
+ ```sh
53
+ devtunnel user login
54
+ pi-ahp-tunnel
55
+ ```
56
+
57
+ Run either command with `--help` for all available options.
58
+
59
+ ### Visual Studio Code
60
+
61
+ VS Code exposes remote Agent Host setup only in its dedicated Agents window, not in a regular editor window. From a regular window, run **Chat: Open Agents Window**.
62
+
63
+ If the remote-host commands are unavailable, or if you want to use a direct connection without signing in to GitHub, add these settings to VS Code's user `settings.json` before opening the Agents window:
64
+
65
+ ```json
66
+ {
67
+ "chat.remoteAgentHostsEnabled": true,
68
+ "chat.agentHost.allowSignedOutWhenUsable": true
69
+ }
70
+ ```
71
+
72
+ The signed-out option is currently experimental and desktop-only. When prompted, choose **Continue Without Signing In**; you do not need to preconfigure a host manually.
73
+
74
+ - **Direct WebSocket:** run **Agents: Add Remote Agent Host...** and paste the URL printed by `pi-ahp`.
75
+ - **Dev Tunnel:** sign in to the same account in VS Code, then run **Agents: Connect to Remote Agent Host via Dev Tunnel**. Tunnel discovery requires sign-in.
76
+
77
+ ## AHP support
78
+
79
+ The following is a high-level mapping to the [official AHP specification](https://microsoft.github.io/agent-host-protocol/specification/overview).
80
+
81
+ Currently supported protocol versions: **0.9.0**
82
+
83
+ 🟢 Supported · 🟡 Planned · 🔴 Out of scope
84
+
85
+ | Feature | Status | Notes |
86
+ | --- | :---: | --- |
87
+ | Connection lifecycle and reconnect | 🟢 | Active work survives a temporary connection loss, but not a host restart |
88
+ | Durable sessions and history | 🟢 | Completed history for the active conversation branch recovers after restart |
89
+ | Streaming chat and pi tool calls | 🟢 | One chat per session |
90
+ | Steering, queues, drafts, and truncation | 🟢 | Drafts and unconsumed queues do not survive a host restart |
91
+ | Models, session setup, and completions | 🟢 | Model and thinking-level selection, working directory, and `@` file completions |
92
+ | Text attachments | 🟢 | Client-provided text, local file references, and embedded UTF-8 text |
93
+ | Files and watches | 🟢 | Host-local `file:` resources only |
94
+ | Interactive terminals | 🟢 | Client-owned; terminals and scrollback end when the host stops |
95
+ | Images and vision | 🟡 | Pass AHP image attachments to vision-capable pi models |
96
+ | Tool catalogue and client tools | 🟡 | Show available pi tools and let connected clients contribute tools |
97
+ | pi customizations | 🟡 | Show and configure loaded extensions, skills, and prompt templates |
98
+ | Changeset views | 🟡 | Expose uncommitted workspace changes |
99
+ | Terminal command detection | 🟡 | Group terminal output by command and exit status |
100
+ | Persistent read and archive controls | 🔴 | pi sessions do not store this metadata |
101
+ | Multiple chats or working directories | 🔴 | A pi session has one active branch and cwd; branches are not simultaneous AHP chats |
102
+ | Custom agents | 🔴 | pi sub-agents are extension tools rather than selectable agents |
103
+ | Elicitation | 🔴 | pi extension dialogs are not persisted as turn input |
104
+ | Tool input and result confirmation | 🔴 | pi has no built-in permission policy |
105
+ | Errored-turn resume | 🔴 | pi cannot reopen a finalized turn |
106
+ | MCP lifecycle and Apps | 🔴 | pi has no built-in MCP runtime; extension implementations are opaque |
107
+ | Annotations | 🔴 | There is no corresponding pi session state |
108
+ | Automations and automation runs | 🔴 | pi has no scheduler or automation-run model |
109
+ | AHP protected-resource authentication | 🔴 | pi manages model-provider credentials itself |
110
+ | OTLP telemetry channels | 🔴 | pi does not provide host telemetry as OTLP |
111
+
112
+ ## License
113
+
114
+ [MIT](LICENSE)
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `pi-ahp` — starts the host and prints the endpoint clients connect to.
4
+ */
5
+ import { loadDirectListenerSettings, SettingsError } from "../host/direct-settings.js";
6
+ import { closeOnSignal, startHost, VERSION } from "../host/serve.js";
7
+ function log(message) {
8
+ process.stderr.write(`${message}\n`);
9
+ }
10
+ function flagValue(args, flag) {
11
+ const index = args.indexOf(flag);
12
+ return index >= 0 ? args[index + 1] : undefined;
13
+ }
14
+ async function main() {
15
+ const args = process.argv.slice(2);
16
+ if (args.includes("--help") || args.includes("-h")) {
17
+ log([
18
+ `pi-ahp v${VERSION}`,
19
+ "",
20
+ "Usage: pi-ahp [--port <n>] [--host <addr>] [--cwd <path>] [--verbose]",
21
+ "",
22
+ "Direct-listener settings persist at ~/.pi/ahp/settings.json; the",
23
+ "port and token are generated on first run.",
24
+ ].join("\n"));
25
+ return;
26
+ }
27
+ const verbose = args.includes("--verbose");
28
+ const settings = await loadDirectListenerSettings();
29
+ const workingDirectory = flagValue(args, "--cwd") ?? process.cwd();
30
+ const server = await startHost({
31
+ host: flagValue(args, "--host") ?? settings.host,
32
+ port: Number(flagValue(args, "--port") ?? settings.port),
33
+ connectionToken: settings.token ?? undefined,
34
+ workingDirectory,
35
+ ...(verbose ? { log } : {}),
36
+ });
37
+ log(settings.token
38
+ ? `pi-ahp listening on ws://${server.host}:${server.port}?token=${settings.token}`
39
+ : `pi-ahp listening on ws://${server.host}:${server.port} (no token — anyone who can reach ${server.host} can drive the agent)`);
40
+ log(`working directory: ${workingDirectory}`);
41
+ closeOnSignal(server);
42
+ }
43
+ try {
44
+ await main();
45
+ }
46
+ catch (error) {
47
+ // A settings problem is the user's to fix, not a crash: print what is wrong
48
+ // and where, without a stack trace pointing into the store.
49
+ if (error instanceof SettingsError) {
50
+ process.stderr.write(`pi-ahp: ${error.message}\n`);
51
+ process.exit(1);
52
+ }
53
+ throw error;
54
+ }
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Serves pi-ahp in the fixed Dev Tunnel shape VS Code discovers. Dev Tunnels
4
+ * controls remote access; the forwarded loopback listener has no URL token.
5
+ */
6
+ import { spawn } from "node:child_process";
7
+ import { startHost, VERSION } from "../host/serve.js";
8
+ import { createTunnel, ensurePort, findTunnel, rename, requireLogin, TunnelError } from "../tunnel/devtunnel.js";
9
+ import { displayLabel, nameLabel, TUNNEL_PORT } from "../tunnel/vscode.js";
10
+ function log(message) {
11
+ process.stderr.write(`${message}\n`);
12
+ }
13
+ async function main() {
14
+ const args = process.argv.slice(2);
15
+ if (args.includes("--help") || args.includes("-h")) {
16
+ log([
17
+ `pi-ahp-tunnel v${VERSION}`,
18
+ "",
19
+ "Usage: pi-ahp-tunnel [--name <label>] [--cwd <path>] [--verbose]",
20
+ "",
21
+ "Reuses this host's tunnel, creating one on the first run. `--name`",
22
+ "sets what VS Code shows in its list; without it, a name given here",
23
+ "or in VS Code earlier is left alone.",
24
+ "",
25
+ "Serves the host over a dev tunnel that VS Code discovers. Needs a",
26
+ "`devtunnel` on PATH, already logged in:",
27
+ "",
28
+ " devtunnel user login -g GitHub account",
29
+ " devtunnel user login Microsoft account (the default)",
30
+ "",
31
+ "Add -d for device-code auth when there is no browser. See",
32
+ "`devtunnel user login --help` for the rest.",
33
+ "",
34
+ "Does not read or modify pi-ahp's direct-listener settings. The",
35
+ `port is fixed by VS Code (${TUNNEL_PORT}); remote access is controlled`,
36
+ "by Microsoft Dev Tunnels rather than an additional URL token.",
37
+ ].join("\n"));
38
+ return;
39
+ }
40
+ const flag = (name) => {
41
+ const index = args.indexOf(name);
42
+ return index >= 0 ? args[index + 1] : undefined;
43
+ };
44
+ const verbose = args.includes("--verbose");
45
+ const workingDirectory = flag("--cwd") ?? process.cwd();
46
+ requireLogin();
47
+ const requested = flag("--name");
48
+ const name = requested ? nameLabel(requested) : undefined;
49
+ if (requested && !name) {
50
+ log(`ignoring --name ${requested}: nothing left after removing characters a label cannot hold`);
51
+ }
52
+ const existing = findTunnel();
53
+ let qualifiedId;
54
+ if (existing) {
55
+ qualifiedId = existing.tunnelId;
56
+ const current = displayLabel(existing.labels);
57
+ if (name && name !== current) {
58
+ rename(qualifiedId, current, name);
59
+ }
60
+ log(`tunnel: ${qualifiedId} (reused${name && name !== current ? `, renamed to ${name}` : ""})`);
61
+ }
62
+ else {
63
+ qualifiedId = createTunnel(name);
64
+ log(`tunnel: ${qualifiedId} (new${name ? `, named ${name}` : ""})`);
65
+ }
66
+ ensurePort(qualifiedId);
67
+ // The host must be up before the tunnel forwards to it, or the first client
68
+ // through the relay hits a closed port.
69
+ const server = await startHost({
70
+ host: "127.0.0.1",
71
+ port: TUNNEL_PORT,
72
+ workingDirectory,
73
+ ...(verbose ? { log } : {}),
74
+ });
75
+ log(`listening on 127.0.0.1:${server.port}, working directory: ${workingDirectory}`);
76
+ log("remote access control: Microsoft Dev Tunnels; local listener: no URL token");
77
+ const host = spawn("devtunnel", ["host", qualifiedId], { stdio: "inherit" });
78
+ let stopping = false;
79
+ // Shutting down goes through the child's `exit`, not alongside it. Killing
80
+ // the child and exiting in the same tick raced: `devtunnel host` outlives
81
+ // us, keeps the relay connection, and the tunnel looks hosted by a process
82
+ // that is gone.
83
+ host.on("exit", (code) => {
84
+ if (!stopping) {
85
+ log(`devtunnel host exited (${code}); shutting down`);
86
+ }
87
+ void server.close().then(() => process.exit(stopping ? 0 : (code ?? 1)));
88
+ });
89
+ const stop = () => {
90
+ if (stopping) {
91
+ // A second Ctrl-C means the wait itself is the problem.
92
+ process.exit(1);
93
+ }
94
+ stopping = true;
95
+ host.kill();
96
+ // A child that will not take SIGTERM should not wedge the terminal;
97
+ // an orphaned relay is the lesser failure.
98
+ setTimeout(() => host.kill("SIGKILL"), 5000).unref();
99
+ };
100
+ process.on("SIGINT", stop);
101
+ process.on("SIGTERM", stop);
102
+ log("");
103
+ log("In VS Code, enable `chat.remoteAgentHostsEnabled` and sign in to the");
104
+ log("same account; the tunnel appears in the agent host list.");
105
+ }
106
+ try {
107
+ await main();
108
+ }
109
+ catch (error) {
110
+ if (error instanceof TunnelError) {
111
+ process.stderr.write(`pi-ahp-tunnel: ${error.message}\n`);
112
+ process.exit(1);
113
+ }
114
+ throw error;
115
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The chat channel — `ahp-chat:/<uuid>`.
3
+ *
4
+ * Every session this host serves has exactly one chat. That is why the agent
5
+ * declares no `multipleChats` capability: its absence is the protocol's way of
6
+ * telling a client not to call `createChat`.
7
+ *
8
+ * @see https://microsoft.github.io/agent-host-protocol/specification/chat-channel
9
+ */
10
+ import { ActionType, ChatOriginKind, MessageKind, SessionStatus, } from "@microsoft/agent-host-protocol";
11
+ import { chatUri } from "../core/channels.js";
12
+ export function initialChatState(uri, title, selection) {
13
+ return {
14
+ resource: uri,
15
+ title,
16
+ status: SessionStatus.Idle,
17
+ modifiedAt: new Date().toISOString(),
18
+ // A session's default chat exists because the user made the session.
19
+ origin: { kind: ChatOriginKind.User },
20
+ turns: [],
21
+ // Seeded before the agent exists. Starting one takes seconds, and a
22
+ // client that subscribes in the meantime would otherwise find an empty
23
+ // model picker and be unable to send. The backend refines this once it
24
+ // is up, if it resolves to something different.
25
+ ...(selection ? { draft: { text: "", origin: { kind: MessageKind.User }, model: selection } } : {}),
26
+ };
27
+ }
28
+ export function chatSummaryOf(state) {
29
+ return {
30
+ resource: state.resource,
31
+ title: state.title,
32
+ status: state.status,
33
+ modifiedAt: state.modifiedAt,
34
+ ...(state.activity !== undefined ? { activity: state.activity } : {}),
35
+ ...(state.origin !== undefined ? { origin: state.origin } : {}),
36
+ ...(state.interactivity !== undefined ? { interactivity: state.interactivity } : {}),
37
+ ...(state.workingDirectories !== undefined ? { workingDirectories: state.workingDirectories } : {}),
38
+ };
39
+ }
40
+ /**
41
+ * Creates a session's default chat and registers it in the session catalog.
42
+ *
43
+ * The chat id is derived from the session id so that the pairing is
44
+ * reconstructible without a lookup table, matching how the session URI already
45
+ * carries pi's session id.
46
+ */
47
+ export function installDefaultChat(host, sessionChannel, sessionId, title, selection) {
48
+ const uri = chatUri(sessionId);
49
+ host.store.create(uri, initialChatState(uri, title, selection));
50
+ const summary = chatSummaryOf(host.store.get(uri));
51
+ host.dispatchServerAction(sessionChannel, { type: ActionType.SessionChatAdded, summary });
52
+ host.dispatchServerAction(sessionChannel, { type: ActionType.SessionDefaultChatChanged, defaultChat: uri });
53
+ return uri;
54
+ }
55
+ function equalUris(left, right) {
56
+ if (!left || !right) {
57
+ return left === right;
58
+ }
59
+ return left.length === right.length && left.every((uri, index) => uri === right[index]);
60
+ }
61
+ function equalSummary(left, right) {
62
+ return (left.resource === right.resource &&
63
+ left.title === right.title &&
64
+ left.status === right.status &&
65
+ left.activity === right.activity &&
66
+ left.modifiedAt === right.modifiedAt &&
67
+ (left.origin === right.origin || JSON.stringify(left.origin) === JSON.stringify(right.origin)) &&
68
+ left.interactivity === right.interactivity &&
69
+ equalUris(left.workingDirectories, right.workingDirectories));
70
+ }
71
+ /**
72
+ * Mirrors a chat's denormalized summary fields into its owning session.
73
+ *
74
+ * Partial updates cannot express removal of an optional JSON field: an
75
+ * `undefined` value disappears on the wire and means "unchanged". Use the
76
+ * action's full-summary upsert form when one of those fields is cleared.
77
+ */
78
+ export function syncChatSummary(host, sessionChannel, chatChannel) {
79
+ const chat = host.store.get(chatChannel);
80
+ const session = host.store.get(sessionChannel);
81
+ const previous = session?.chats.find((summary) => summary.resource === chatChannel);
82
+ if (!chat || !previous) {
83
+ return false;
84
+ }
85
+ const current = chatSummaryOf(chat);
86
+ if (equalSummary(previous, current)) {
87
+ return false;
88
+ }
89
+ const clearsOptional = (previous.activity !== undefined && current.activity === undefined) ||
90
+ (previous.origin !== undefined && current.origin === undefined) ||
91
+ (previous.interactivity !== undefined && current.interactivity === undefined) ||
92
+ (previous.workingDirectories !== undefined && current.workingDirectories === undefined);
93
+ if (clearsOptional) {
94
+ host.dispatchServerAction(sessionChannel, { type: ActionType.SessionChatAdded, summary: current });
95
+ }
96
+ else {
97
+ const { resource: _resource, ...changes } = current;
98
+ host.dispatchServerAction(sessionChannel, {
99
+ type: ActionType.SessionChatUpdated,
100
+ chat: chatChannel,
101
+ changes,
102
+ });
103
+ }
104
+ return true;
105
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The root channel — `ahp-root://`.
3
+ *
4
+ * Exactly one root channel exists per host. It carries the agents this host can
5
+ * speak to plus host-level config. The session catalogue is deliberately *not*
6
+ * root state: clients fetch it with `listSessions` and patch it from
7
+ * `root/session*` notifications.
8
+ *
9
+ * @see https://microsoft.github.io/agent-host-protocol/specification/root-channel
10
+ */
11
+ import { ROOT_CHANNEL } from "../core/channels.js";
12
+ function initialRootState(agents = []) {
13
+ return { agents, activeSessions: 0 };
14
+ }
15
+ /** Registers `ahp-root://` on the host. Must run before any client connects. */
16
+ export function installRootChannel(host, agents = []) {
17
+ host.store.create(ROOT_CHANNEL, initialRootState(agents));
18
+ }
19
+ // ── Catalogue notifications ───────────────────────────────────────────────
20
+ // Ephemeral and never replayed on reconnect; after reconnecting a client
21
+ // re-fetches the catalogue with `listSessions`.
22
+ export function notifySessionAdded(host, summary) {
23
+ host.notify(ROOT_CHANNEL, "root/sessionAdded", { summary });
24
+ }
25
+ export function notifySessionRemoved(host, session) {
26
+ host.notify(ROOT_CHANNEL, "root/sessionRemoved", { session });
27
+ }
28
+ export function notifySessionSummaryChanged(host, session, changes) {
29
+ host.notify(ROOT_CHANNEL, "root/sessionSummaryChanged", { session, changes });
30
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The session channel — `ahp-session:/<uuid>`.
3
+ *
4
+ * A session is the coordination scope; the conversation itself lives on a chat
5
+ * channel underneath it. Creation is asynchronous by design: the host returns
6
+ * immediately with `lifecycle: 'creating'` and dispatches `session/ready` or
7
+ * `session/creationFailed` once backend startup settles, so a slow agent start
8
+ * never blocks the client's round-trip.
9
+ *
10
+ * @see https://microsoft.github.io/agent-host-protocol/specification/session-channel
11
+ */
12
+ import { SessionLifecycle, SessionStatus, } from "@microsoft/agent-host-protocol";
13
+ import { pathToFileUri } from "../core/uri.js";
14
+ export function initialSessionState(provider, title, workingDirectory) {
15
+ return {
16
+ provider,
17
+ title,
18
+ status: SessionStatus.Idle,
19
+ lifecycle: SessionLifecycle.Creating,
20
+ workingDirectories: [pathToFileUri(workingDirectory)],
21
+ activeClients: [],
22
+ chats: [],
23
+ };
24
+ }
25
+ /** The low five bits encode activity; higher bits carry independent metadata flags. */
26
+ const STATUS_ACTIVITY_MASK = (1 << 5) - 1;
27
+ function timestamp(summary) {
28
+ const value = Date.parse(summary.modifiedAt);
29
+ return Number.isFinite(value) ? value : Number.NEGATIVE_INFINITY;
30
+ }
31
+ function mostRecent(chats, matches) {
32
+ let latest;
33
+ for (const chat of chats) {
34
+ if (matches(chat) && (!latest || timestamp(chat) > timestamp(latest))) {
35
+ latest = chat;
36
+ }
37
+ }
38
+ return latest;
39
+ }
40
+ /**
41
+ * Projects the session-level summary fields AHP derives from its chat catalog.
42
+ *
43
+ * The current host exposes one chat, so this is a direct pass-through today.
44
+ * Keeping the complete 0.9 rule here makes the projection deterministic and
45
+ * avoids teaching the pi adapter about protocol status bits.
46
+ */
47
+ export function aggregateSessionChats(state) {
48
+ if (state.chats.length === 0) {
49
+ return {
50
+ status: state.status,
51
+ ...(state.activity !== undefined ? { activity: state.activity } : {}),
52
+ };
53
+ }
54
+ const latest = mostRecent(state.chats, () => true);
55
+ if (!latest) {
56
+ return { status: state.status };
57
+ }
58
+ let driver = state.chats.find((chat) => chat.resource === state.defaultChat) ?? latest;
59
+ const inputNeeded = mostRecent(state.chats, (chat) => (chat.status & SessionStatus.InputNeeded) === SessionStatus.InputNeeded);
60
+ const error = mostRecent(state.chats, (chat) => (chat.status & SessionStatus.Error) === SessionStatus.Error);
61
+ if (inputNeeded) {
62
+ driver = inputNeeded;
63
+ }
64
+ else if (error) {
65
+ driver = error;
66
+ }
67
+ const metadataBits = state.status & ~STATUS_ACTIVITY_MASK;
68
+ const activityBits = driver.status & STATUS_ACTIVITY_MASK;
69
+ return {
70
+ status: (metadataBits | activityBits),
71
+ ...(driver.activity !== undefined ? { activity: driver.activity } : {}),
72
+ modifiedAt: latest.modifiedAt,
73
+ };
74
+ }
75
+ export function sessionSummaryOf(resource, createdAt, state, meta) {
76
+ const aggregate = aggregateSessionChats(state);
77
+ return {
78
+ resource,
79
+ provider: state.provider,
80
+ title: state.title,
81
+ status: aggregate.status,
82
+ // Root summary activity is deliberately omitted for AHP 0.9: its partial
83
+ // update shape cannot distinguish "clear" from "unchanged" on JSON wire.
84
+ createdAt,
85
+ modifiedAt: aggregate.modifiedAt ?? createdAt,
86
+ ...(state.workingDirectories ? { workingDirectories: state.workingDirectories } : {}),
87
+ ...(meta ? { _meta: meta } : {}),
88
+ };
89
+ }
@@ -0,0 +1,9 @@
1
+ /** Root catalogue projection; terminal process handles never enter protocol state. */
2
+ export function terminalInfo(resource, state) {
3
+ return {
4
+ resource,
5
+ title: state.title,
6
+ claim: state.claim,
7
+ lifecycle: state.lifecycle,
8
+ };
9
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Channel URI scheme helpers.
3
+ *
4
+ * Channels are the routing key for the whole protocol: every command and every
5
+ * notification carries `params.channel`, so `(method, channel)` is enough to
6
+ * dispatch a message.
7
+ *
8
+ * @see https://microsoft.github.io/agent-host-protocol/specification/subscriptions
9
+ */
10
+ export const ROOT_CHANNEL = "ahp-root://";
11
+ const SESSION_SCHEME = "ahp-session:";
12
+ const CHAT_SCHEME = "ahp-chat:";
13
+ const TERMINAL_SCHEME = "ahp-terminal:";
14
+ const CHANGESET_SCHEME = "ahp-changeset:";
15
+ export const RESOURCE_WATCH_SCHEME = "ahp-resource-watch:";
16
+ /** Whether an action namespace belongs to the reducer behind a channel. */
17
+ export function actionBelongsToChannel(type, kind) {
18
+ return typeof type === "string" && type.startsWith(`${kind}/`);
19
+ }
20
+ function isRootChannel(uri) {
21
+ return uri === ROOT_CHANNEL;
22
+ }
23
+ function isSessionChannel(uri) {
24
+ return uri.startsWith(`${SESSION_SCHEME}/`);
25
+ }
26
+ export function isChatChannel(uri) {
27
+ return uri.startsWith(`${CHAT_SCHEME}/`);
28
+ }
29
+ /**
30
+ * Classifies a channel URI, or `undefined` for a scheme this host does not
31
+ * serve.
32
+ *
33
+ * Deliberately strict: it drives `subscribe`, where guessing wrong would create
34
+ * a channel with the wrong reducer. A command that creates a resource can
35
+ * register its client-chosen URI with an explicit kind instead.
36
+ */
37
+ export function channelKind(uri) {
38
+ if (isRootChannel(uri)) {
39
+ return "root";
40
+ }
41
+ if (isSessionChannel(uri)) {
42
+ return "session";
43
+ }
44
+ if (isChatChannel(uri)) {
45
+ return "chat";
46
+ }
47
+ if (uri.startsWith(`${TERMINAL_SCHEME}/`)) {
48
+ return "terminal";
49
+ }
50
+ if (uri.startsWith(`${CHANGESET_SCHEME}/`)) {
51
+ return "changeset";
52
+ }
53
+ if (uri.startsWith(`${RESOURCE_WATCH_SCHEME}/`)) {
54
+ return "resourceWatch";
55
+ }
56
+ return undefined;
57
+ }
58
+ function parseSingleSegmentChannel(uri) {
59
+ const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/([^/?#]+)$/.exec(uri);
60
+ const scheme = match?.[1];
61
+ const id = match?.[2];
62
+ return scheme && id ? { scheme: scheme.toLowerCase(), id } : undefined;
63
+ }
64
+ /**
65
+ * Identifies a session from its canonical scheme or explicit provider aliases
66
+ * given as bare scheme names. Shape alone never makes an unknown URI a session.
67
+ */
68
+ export function sessionIdFromUri(uri, providerAliases = []) {
69
+ const parsed = parseSingleSegmentChannel(uri);
70
+ if (!parsed) {
71
+ return undefined;
72
+ }
73
+ const canonical = SESSION_SCHEME.slice(0, -1);
74
+ return parsed.scheme === canonical || providerAliases.some((alias) => parsed.scheme === alias.toLowerCase())
75
+ ? parsed.id
76
+ : undefined;
77
+ }
78
+ export function sessionUri(sessionId) {
79
+ return `${SESSION_SCHEME}/${sessionId}`;
80
+ }
81
+ /** `ahp-chat:/<id>` → `<id>`. Returns `undefined` when the URI is not a chat. */
82
+ export function chatIdFromUri(uri) {
83
+ return isChatChannel(uri) ? uri.slice(`${CHAT_SCHEME}/`.length) || undefined : undefined;
84
+ }
85
+ export function chatUri(chatId) {
86
+ return `${CHAT_SCHEME}/${chatId}`;
87
+ }