@anusornneal/chat-relay 1.1.1 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -209,52 +209,47 @@ Optional Cloudflare-pressure circuit breakers can be configured with `USAGE_RECO
209
209
 
210
210
  ## Account-scoped Learn
211
211
 
212
- Chat Relay can persist small, structured pieces of execution context per authenticated account. Learn is **not model training** and it does not capture conversations or tool payloads automatically.
212
+ Chat Relay can persist small, structured pieces of execution context per authenticated account. Learn is **not model training** and it does not capture conversations or ordinary tool payloads automatically.
213
213
 
214
214
  The MCP surface is:
215
215
 
216
- - `learn_get` reads explicit memories for selected scopes.
217
- - `learn_put` creates or updates one memory.
216
+ - `learn_prepare` performs one explicit, relevance-aware preparation pass for the current task. It can combine global, project, and agent memories, then rank and compact them into one advisory context envelope.
217
+ - `learn_get` reads raw memories for selected scopes when targeted inspection is needed.
218
+ - `learn_put` creates or updates one durable memory when Chat decides a reusable signal is worth keeping.
218
219
  - `learn_delete` removes one memory.
219
220
  - `learn_feedback` records positive or negative feedback on one memory.
220
221
 
221
222
  Memories are partitioned by authenticated account using a dedicated Learning Durable Object selected from the server-side `user.id`. Callers cannot provide or override an account id. Supported scopes are `global`, `project`, and `agent`; project and agent memories require a scope key.
222
223
 
223
- The first version is intentionally lightweight: there are no embeddings, vector database, local LLM, transcript ingestion, or per-tool-call writes. A normal tool call causes no Learn storage write. Storage changes happen only when an explicit Learn mutation is requested. Each account is capped at 512 memories, each memory content field is capped at 4,000 characters, and reads return at most 100 records. Do not store credentials, tokens, secrets, raw tool payloads, terminal output, file contents, or screenshots in Learn.
224
+ Learn remains intentionally lightweight: there are no embeddings, vector database, local LLM, transcript ingestion, or per-tool-call Learn reads/writes. A normal Relay tool call does **not** touch the Learning Durable Object. Storage changes happen only when an explicit Learn mutation is requested. Each account is capped at 512 memories, each memory content field is capped at 4,000 characters, and raw reads return at most 100 records. Do not store credentials, tokens, secrets, raw tool payloads, terminal output, file contents, or screenshots in Learn.
224
225
 
226
+ ## Explicit one-shot Learn preparation
225
227
 
226
- ## Progressive Learn bootstrap and routing
227
-
228
- Learn context is loaded progressively so a fresh ChatGPT conversation does not need to remember to call `learn_get` before using Relay.
228
+ Chat decides whether learned context is useful for the task. When it is, Chat calls `learn_prepare` once and reuses the returned context for the rest of that task instead of re-preparing before every tool call.
229
229
 
230
230
  ```mermaid
231
231
  flowchart TD
232
- U[User starts or continues a chat] --> M[ChatGPT calls Relay]
233
- M --> A[Authenticate account]
234
- A --> G{Global context loaded in this MCP session?}
235
- G -- No --> LG[Read global Learn once]
236
- G -- Yes --> S[Continue]
237
- LG --> S
238
- S --> P{Concrete project signal? path / cwd / repo}
239
- P -- Yes --> PR[Match explicit project-root hint]
240
- PR --> LP[Read project Learn once]
241
- P -- No --> AG
242
- LP --> AG
243
- AG{Agent selected or safely resolved?}
244
- AG -- Yes --> LA[Read agent Learn once]
245
- AG -- No --> E
246
- LA --> E
247
- E[Attach bounded learnedContext envelope] --> R[ChatGPT chooses action and tool]
248
- R --> SEC[Relay enforces auth, grants, allowedRoots and capabilities]
249
- SEC --> X[Execute]
232
+ U[User starts or continues a task] --> D{Would prior learned context materially help?}
233
+ D -- No --> R[Use ordinary Relay tools]
234
+ D -- Yes --> P[Chat calls learn_prepare once]
235
+ P --> G[Read account-global Learn]
236
+ G --> K[Resolve explicit or project-root project]
237
+ K --> PJ[Read project Learn when available]
238
+ PJ --> A[Resolve explicit or preferred agent]
239
+ A --> AG[Read agent Learn when available]
240
+ AG --> Q[Rank by task query + tool hint + scope]
241
+ Q --> C[Compact to bounded advisory context]
242
+ C --> R2[Chat reuses prepared context for the task]
243
+ R2 --> X[Use ordinary Relay tools without more implicit Learn reads]
250
244
  ```
251
245
 
252
246
  The decision boundary is deliberate:
253
247
 
254
- - **Relay decides mechanical routing only:** authenticated account, whether a scope was already loaded, project identity from explicit `project-root:<projectKey>` memories, explicit/resolved agent, and available permissions/capabilities.
255
- - **ChatGPT decides semantic actions and tools:** whether to read files, search, edit, run terminal commands, use desktop control, or re-plan after a failure.
256
- - Learned hints never override authorization, grants, allowed roots, destructive-tool policy, or capability checks.
248
+ - **Chat decides semantic Learn use:** whether to prepare context, whether a correction/preference/workflow is durable enough to learn, and when a targeted raw `learn_get` is needed.
249
+ - **Relay performs mechanical preparation only after `learn_prepare` is explicitly called:** account isolation, project routing from explicit `project-root:<projectKey>` memories or explicit `projectKey`, preferred-agent routing, bounded reads, relevance ranking, and compaction.
250
+ - **Ordinary tools stay hot-path clean:** `ping_agent`, file tools, terminal tools, desktop tools, and other MCP calls do not automatically read, rank, inject, or write Learn.
251
+ - Learned hints remain advisory and never override authorization, grants, allowed roots, destructive-tool policy, capability checks, safety, or the current user request.
257
252
 
258
- Routing hints are explicit memories. A global `project_context` memory with key `project-root:<projectKey>` stores the concrete project root. A `preferred-agent` memory may exist in project scope (preferred) or global scope (fallback); Relay surfaces it in `routingContext` as guidance and does not execute or retry a tool solely because of that hint. No project is guessed when no explicit root hint matches.
253
+ Routing hints are explicit memories. A global `project_context` memory with key `project-root:<projectKey>` stores the concrete project root. A `preferred-agent` memory may exist in project scope (preferred) or global scope (fallback). `learn_prepare` can also take explicit `projectKey` and `agentId` values when Chat already knows them.
259
254
 
260
- The intended read budget is bounded by an in-memory warm-cache: global context is normally read once per conversation/session, each activated project once, and each activated agent once. A Worker isolate restart/eviction may cause a scope to be read again; this is intentionally best-effort so bootstrap performs no durable session writes. Learned content is advisory user memory, not system/developer instruction authority.
255
+ `learn_prepare` is intentionally one-shot and stateless at the Worker level. There is no warm session cache or durable Learn session state to maintain. This prevents Learn from becoming an implicit per-tool CPU/subrequest tax while still allowing relevance-aware context preparation when it is actually useful.
@@ -0,0 +1,204 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ const execFileAsync = promisify(execFile);
7
+ const GIT_MAX_BUFFER = 256 * 1024;
8
+ const DEFAULT_PROTECTED_BRANCHES = new Set(["main", "master", "develop"]);
9
+
10
+ function within(root, target) {
11
+ const relative = path.relative(root, target);
12
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
13
+ }
14
+
15
+ function comparablePath(value, platform = process.platform) {
16
+ const resolved = path.resolve(value);
17
+ return platform === "win32" ? resolved.toLowerCase() : resolved;
18
+ }
19
+
20
+ function parseWorktrees(output) {
21
+ const entries = [];
22
+ let current = null;
23
+
24
+ for (const line of String(output || "").split(/\r?\n/)) {
25
+ if (line.startsWith("worktree ")) {
26
+ if (current) entries.push(current);
27
+ current = { path: line.slice("worktree ".length), branch: null, detached: false };
28
+ continue;
29
+ }
30
+ if (!current) continue;
31
+ if (line.startsWith("branch refs/heads/")) current.branch = line.slice("branch refs/heads/".length);
32
+ if (line === "detached") current.detached = true;
33
+ }
34
+
35
+ if (current) entries.push(current);
36
+ return entries;
37
+ }
38
+
39
+ async function runGit(cwd, args, options = {}) {
40
+ try {
41
+ const result = await execFileAsync("git", ["-C", cwd, ...args], {
42
+ encoding: "utf8",
43
+ maxBuffer: GIT_MAX_BUFFER,
44
+ windowsHide: true,
45
+ });
46
+ return {
47
+ ok: true,
48
+ stdout: String(result.stdout || ""),
49
+ stderr: String(result.stderr || ""),
50
+ exitCode: 0,
51
+ };
52
+ } catch (error) {
53
+ const exitCode = Number.isInteger(error?.code) ? Number(error.code) : 1;
54
+ if (Array.isArray(options.allowExitCodes) && options.allowExitCodes.includes(exitCode)) {
55
+ return {
56
+ ok: false,
57
+ stdout: String(error?.stdout || ""),
58
+ stderr: String(error?.stderr || ""),
59
+ exitCode,
60
+ };
61
+ }
62
+ const detail = String(error?.stderr || error?.message || "git_command_failed").trim();
63
+ const wrapped = new Error(options.errorCode || "git_command_failed");
64
+ wrapped.cause = detail;
65
+ throw wrapped;
66
+ }
67
+ }
68
+
69
+ export class GitWorktreeManager {
70
+ constructor(roots = [], options = {}) {
71
+ this.roots = Array.isArray(roots) ? roots.map((root) => path.resolve(String(root))) : [];
72
+ this.platform = String(options.platform || process.platform);
73
+ }
74
+
75
+ async #resolveAllowedExisting(input) {
76
+ if (typeof input !== "string" || input.length === 0 || input.length > 2048) {
77
+ throw new Error("invalid_path");
78
+ }
79
+ const target = await fs.realpath(path.resolve(input));
80
+ for (const root of this.roots) {
81
+ const canonicalRoot = await fs.realpath(root).catch(() => path.resolve(root));
82
+ if (within(canonicalRoot, target)) return target;
83
+ }
84
+ throw new Error("path_not_allowed");
85
+ }
86
+
87
+ async cleanup(repoPathInput, worktreePathInput) {
88
+ let repoPath;
89
+ let worktreePath;
90
+ try {
91
+ repoPath = await this.#resolveAllowedExisting(repoPathInput);
92
+ worktreePath = await this.#resolveAllowedExisting(worktreePathInput);
93
+ } catch (error) {
94
+ return { ok: false, error: error instanceof Error ? error.message : "path_validation_failed" };
95
+ }
96
+
97
+ if (comparablePath(repoPath, this.platform) === comparablePath(worktreePath, this.platform)) {
98
+ return { ok: false, error: "repo_path_is_target_worktree" };
99
+ }
100
+
101
+ let repoRoot;
102
+ try {
103
+ const rootResult = await runGit(repoPath, ["rev-parse", "--show-toplevel"], { errorCode: "not_a_git_repository" });
104
+ repoRoot = await this.#resolveAllowedExisting(rootResult.stdout.trim());
105
+ } catch (error) {
106
+ return { ok: false, error: error instanceof Error ? error.message : "not_a_git_repository" };
107
+ }
108
+
109
+ let worktrees;
110
+ try {
111
+ const listed = await runGit(repoPath, ["worktree", "list", "--porcelain"], { errorCode: "worktree_list_failed" });
112
+ worktrees = parseWorktrees(listed.stdout);
113
+ } catch (error) {
114
+ return { ok: false, error: error instanceof Error ? error.message : "worktree_list_failed" };
115
+ }
116
+
117
+ const primary = worktrees[0];
118
+ if (!primary) return { ok: false, error: "primary_worktree_not_found" };
119
+ const repoKey = comparablePath(repoRoot, this.platform);
120
+ if (comparablePath(primary.path, this.platform) !== repoKey) {
121
+ return { ok: false, error: "repo_path_not_primary_worktree" };
122
+ }
123
+
124
+ const targetKey = comparablePath(worktreePath, this.platform);
125
+ const target = worktrees.find((entry) => comparablePath(entry.path, this.platform) === targetKey);
126
+ if (!target) return { ok: false, error: "worktree_not_registered" };
127
+
128
+ if (repoKey === targetKey) {
129
+ return { ok: false, error: "primary_worktree_protected" };
130
+ }
131
+ if (target.detached || !target.branch) return { ok: false, error: "detached_worktree_not_supported" };
132
+ if (DEFAULT_PROTECTED_BRANCHES.has(target.branch.toLowerCase())) {
133
+ return { ok: false, error: "protected_branch", branch: target.branch };
134
+ }
135
+
136
+ let dirty;
137
+ try {
138
+ const status = await runGit(worktreePath, ["status", "--porcelain=v1", "--untracked-files=all"], { errorCode: "worktree_status_failed" });
139
+ dirty = status.stdout.trim();
140
+ } catch (error) {
141
+ return { ok: false, error: error instanceof Error ? error.message : "worktree_status_failed" };
142
+ }
143
+ if (dirty) {
144
+ return {
145
+ ok: false,
146
+ error: "dirty_worktree",
147
+ branch: target.branch,
148
+ changedEntries: dirty.split(/\r?\n/).filter(Boolean).length,
149
+ };
150
+ }
151
+
152
+ let repoHead = "HEAD";
153
+ try {
154
+ const head = await runGit(repoPath, ["rev-parse", "--abbrev-ref", "HEAD"], { errorCode: "repo_head_failed" });
155
+ repoHead = head.stdout.trim() || "HEAD";
156
+ const merged = await runGit(
157
+ repoPath,
158
+ ["merge-base", "--is-ancestor", `refs/heads/${target.branch}`, "HEAD"],
159
+ { allowExitCodes: [1], errorCode: "merge_check_failed" },
160
+ );
161
+ if (!merged.ok) {
162
+ return { ok: false, error: "branch_not_merged", branch: target.branch, mergedInto: repoHead };
163
+ }
164
+ } catch (error) {
165
+ return { ok: false, error: error instanceof Error ? error.message : "merge_check_failed" };
166
+ }
167
+
168
+ try {
169
+ await runGit(repoPath, ["worktree", "remove", worktreePath], { errorCode: "worktree_remove_failed" });
170
+ await runGit(repoPath, ["worktree", "prune"], { errorCode: "worktree_prune_failed" });
171
+ } catch (error) {
172
+ return {
173
+ ok: false,
174
+ error: error instanceof Error ? error.message : "worktree_remove_failed",
175
+ branch: target.branch,
176
+ };
177
+ }
178
+
179
+ try {
180
+ await runGit(repoPath, ["branch", "-d", "--", target.branch], { errorCode: "branch_delete_failed" });
181
+ } catch (error) {
182
+ return {
183
+ ok: false,
184
+ error: error instanceof Error ? error.message : "branch_delete_failed",
185
+ branch: target.branch,
186
+ worktreeRemoved: true,
187
+ branchDeleted: false,
188
+ };
189
+ }
190
+
191
+ return {
192
+ ok: true,
193
+ repoPath: repoRoot,
194
+ worktreePath,
195
+ branch: target.branch,
196
+ mergedInto: repoHead,
197
+ worktreeRemoved: true,
198
+ pruned: true,
199
+ branchDeleted: true,
200
+ };
201
+ }
202
+ }
203
+
204
+ export { parseWorktrees };
@@ -1,6 +1,7 @@
1
1
  import WebSocket from "ws";
2
2
  import { DesktopManager, createDesktopPlatformAdapter } from "./desktop-manager.mjs";
3
3
  import { FileManager } from "./file-manager.mjs";
4
+ import { GitWorktreeManager } from "./git-worktree-manager.mjs";
4
5
  import { ProcessManager } from "./process-manager.mjs";
5
6
  import { TerminalManager } from "./terminal-manager.mjs";
6
7
  import { CapabilityScheduler } from "./capability-scheduler.mjs";
@@ -72,6 +73,7 @@ const connectionState = new AgentConnectionState({
72
73
  heartbeatMs: process.env.AGENT_HEARTBEAT_MS,
73
74
  });
74
75
  const files = new FileManager(process.env.ALLOWED_ROOTS);
76
+ const gitWorktrees = new GitWorktreeManager(files.getRoots(), { platform: process.platform });
75
77
  const processes = new ProcessManager();
76
78
  const desktop = new DesktopManager({
77
79
  enabled: desktopEnabled,
@@ -226,6 +228,9 @@ async function handlePayload(payload) {
226
228
  case "fs.search.results":
227
229
  return files.getSearchResults(payload.sessionId, payload.offset, payload.length);
228
230
 
231
+ case "git.worktree.cleanup":
232
+ return gitWorktrees.cleanup(payload.repoPath, payload.worktreePath);
233
+
229
234
  case "process.list":
230
235
  return processes.list(payload.filter);
231
236
  case "process.kill":
@@ -484,6 +489,10 @@ function connect() {
484
489
  }
485
490
  return;
486
491
  }
492
+ if (message?.control === "learn_activity") {
493
+ emitUi("learn", { change: message.change && typeof message.change === "object" ? message.change : {} });
494
+ return;
495
+ }
487
496
  if (message?.control === "credential_revoked") {
488
497
  requireReauthorization("credential_revoked");
489
498
  return;
@@ -35,6 +35,7 @@ export function getAgentCapabilities(options = {}) {
35
35
  "filesystem.move",
36
36
  "filesystem.delete",
37
37
  "filesystem.search",
38
+ "git.worktree.cleanup",
38
39
  "process.list",
39
40
  "process.kill",
40
41
  ];
@@ -1,4 +1,4 @@
1
- export const RELAY_HEALTH_CHECK_INTERVAL_MS = 5 * 60 * 1000;
1
+ export const RELAY_HEALTH_CHECK_INTERVAL_MS = 15 * 60 * 1000;
2
2
  export const RELAY_HEALTH_CHECK_TIMEOUT_MS = 8 * 1000;
3
3
  export const RELAY_HEALTH_LIMITED_INTERVAL_MS = 60 * 60 * 1000;
4
4
  export const RELAY_HEALTH_CLOUDFLARE_ERROR_INTERVAL_MS = 15 * 60 * 1000;
@@ -101,6 +101,7 @@ export async function checkRelayHealth(relayUrl, {
101
101
  healthUrl.pathname = `${healthUrl.pathname.replace(/\/+$/, "")}/status`;
102
102
  healthUrl.search = "";
103
103
  if (agentId) healthUrl.searchParams.set("agentId", String(agentId));
104
+ healthUrl.searchParams.set("compact", "1");
104
105
  healthUrl.hash = "";
105
106
  } catch {
106
107
  return { state: "unavailable" };
@@ -135,7 +136,7 @@ export async function checkRelayHealth(relayUrl, {
135
136
 
136
137
  export function startRelayHealthMonitor(relayUrl, {
137
138
  onStatus,
138
- // Per active TUI, this adds 288 Worker requests and up to 864 DO fetches daily.
139
+ // Per active TUI, this adds 96 Worker requests and up to 288 DO fetches daily.
139
140
  intervalMs = RELAY_HEALTH_CHECK_INTERVAL_MS,
140
141
  ...checkOptions
141
142
  } = {}) {
package/cli/tui.mjs CHANGED
@@ -473,6 +473,24 @@ export class RemoteTui {
473
473
  item.durationMs = message.durationMs;
474
474
  if (message.error && message.ok === false) item.summary += ` · ${truncate(message.error, 48)}`;
475
475
  }
476
+ } else if (message.event === "learn") {
477
+ const change = message.change && typeof message.change === "object" ? message.change : {};
478
+ const marker = {
479
+ created: "+",
480
+ updated: "~",
481
+ reinforced: "^",
482
+ weakened: "v",
483
+ removed: "-",
484
+ }[String(change.type || "")] || "~";
485
+ const detail = String(change.summary || change.key || "Learn updated").replace(/\s+/g, " ").trim();
486
+ this.appendTransaction({
487
+ requestId: "learn-" + String(change.eventId || Date.now()),
488
+ at: change.at || message.at || new Date().toISOString(),
489
+ action: "learn",
490
+ summary: "Learn " + marker + " " + truncate(detail, 120),
491
+ status: "done",
492
+ ok: true,
493
+ });
476
494
  } else if (message.event === "system") {
477
495
  this.appendTransaction({
478
496
  requestId: "system-" + Date.now() + "-" + Math.random(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anusornneal/chat-relay",
3
- "version": "1.1.1",
3
+ "version": "1.2.1",
4
4
  "description": "Zero-checkout remote MCP agent for ChatGPT with terminal, filesystem, process, multi-user, and multi-agent support.",
5
5
  "type": "module",
6
6
  "bin": {