@anusornneal/chat-relay 1.2.0 → 1.2.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/README.md CHANGED
@@ -179,7 +179,7 @@ $env:CHAT_RELAY_SOAK_ITERATIONS=100000; npm run test:soak
179
179
 
180
180
  ## Administration
181
181
 
182
- Administration is separate from the public MCP interface. The admin tooling manages users, agents, grants, lifecycle, quotas, audit data, and operational cleanup.
182
+ Administration is separate from the public MCP interface. The admin tooling manages users, agents, grants, lifecycle, audit data, and operational cleanup.
183
183
 
184
184
  Operator commands are available through:
185
185
 
@@ -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":
@@ -485,7 +490,12 @@ function connect() {
485
490
  return;
486
491
  }
487
492
  if (message?.control === "learn_activity") {
488
- emitUi("learn", { change: message.change && typeof message.change === "object" ? message.change : {} });
493
+ const activity = message.activity && typeof message.activity === "object" ? message.activity : null;
494
+ const change = message.change && typeof message.change === "object" ? message.change : null;
495
+ emitUi("learn", {
496
+ ...(activity ? { activity } : {}),
497
+ ...(change ? { change } : {}),
498
+ });
489
499
  return;
490
500
  }
491
501
  if (message?.control === "credential_revoked") {
@@ -504,7 +514,8 @@ function connect() {
504
514
  ? String(message.payload.action ?? "unknown")
505
515
  : "unknown";
506
516
  const callSummary = humanizeToolCall(message.payload);
507
- emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary });
517
+ const requestBytes = Buffer.byteLength(JSON.stringify(message), "utf8");
518
+ emitUi("tool:start", { requestId: message.requestId, action, summary: callSummary, requestBytes });
508
519
  let scheduleMeta = { lane: "unknown", queueWaitMs: 0, queueDepthAtStart: 0, activeAtStart: 0 };
509
520
  let handlerDurationMs = 0;
510
521
  try {
@@ -531,19 +542,22 @@ function connect() {
531
542
  ok: !(result && typeof result === "object" && result.ok === false),
532
543
  });
533
544
  if (recentCalls.length > 100) recentCalls.shift();
545
+ const responseMeta = {
546
+ agentQueueWaitMs: scheduleMeta.queueWaitMs,
547
+ agentHandlerMs: handlerDurationMs,
548
+ lane: scheduleMeta.lane,
549
+ };
550
+ const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, result, responseMeta), "utf8");
534
551
  emitUi("tool:end", {
535
552
  requestId: message.requestId,
536
553
  action,
537
554
  summary: callSummary,
538
555
  ok: !(result && typeof result === "object" && result.ok === false),
539
556
  durationMs: Date.now() - startedAt,
557
+ responseBytes,
540
558
  ...(result && typeof result === "object" && result.ok === false && result.error ? { error: String(result.error) } : {}),
541
559
  });
542
- sendSocketResponse(socket, message.requestId, result, {
543
- agentQueueWaitMs: scheduleMeta.queueWaitMs,
544
- agentHandlerMs: handlerDurationMs,
545
- lane: scheduleMeta.lane,
546
- });
560
+ sendSocketResponse(socket, message.requestId, result, responseMeta);
547
561
  } catch (error) {
548
562
  recentCalls.push({
549
563
  at: new Date().toISOString(),
@@ -557,18 +571,21 @@ function connect() {
557
571
  error: error instanceof Error ? error.message : "agent_error",
558
572
  });
559
573
  if (recentCalls.length > 100) recentCalls.shift();
574
+ const errorPayload = {
575
+ ok: false,
576
+ error: error instanceof Error ? error.message : "agent_error",
577
+ };
578
+ const responseBytes = Buffer.byteLength(serializeResponse(message.requestId, errorPayload), "utf8");
560
579
  emitUi("tool:end", {
561
580
  requestId: message.requestId,
562
581
  action,
563
582
  summary: callSummary,
564
583
  ok: false,
565
584
  durationMs: Date.now() - startedAt,
566
- error: error instanceof Error ? error.message : "agent_error",
567
- });
568
- sendSocketResponse(socket, message.requestId, {
569
- ok: false,
570
- error: error instanceof Error ? error.message : "agent_error",
585
+ responseBytes,
586
+ error: errorPayload.error,
571
587
  });
588
+ sendSocketResponse(socket, message.requestId, errorPayload);
572
589
  }
573
590
  });
574
591
 
@@ -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
  ];
package/cli/tui.mjs CHANGED
@@ -191,6 +191,13 @@ function formatDuration(ms, status) {
191
191
  return (value / 1000).toFixed(value < 10000 ? 1 : 0) + "s";
192
192
  }
193
193
 
194
+ export function formatBytes(bytes) {
195
+ const value = Math.max(0, Number(bytes) || 0);
196
+ if (value < 1024) return Math.round(value) + " B";
197
+ if (value < 1024 * 1024) return (value / 1024).toFixed(value < 10 * 1024 ? 1 : 0) + " KB";
198
+ return (value / (1024 * 1024)).toFixed(value < 10 * 1024 * 1024 ? 1 : 0) + " MB";
199
+ }
200
+
194
201
  function clock(value) {
195
202
  const date = value ? new Date(value) : new Date();
196
203
  if (Number.isNaN(date.getTime())) return "--:--:--";
@@ -239,7 +246,11 @@ export function formatTransactionRows(item, width = 110, { color = false } = {})
239
246
  const prefixWidth = terminalCellWidth(prefix);
240
247
  const continuationPrefix = " ".repeat(prefixWidth);
241
248
  const duration = formatDuration(item.durationMs, item.status);
242
- const suffix = " " + duration.padStart(8);
249
+ const transfer = [
250
+ Number.isFinite(Number(item.requestBytes)) ? "↑ " + formatBytes(item.requestBytes) : null,
251
+ Number.isFinite(Number(item.responseBytes)) ? "↓ " + formatBytes(item.responseBytes) : null,
252
+ ].filter(Boolean).join(" ");
253
+ const suffix = " " + (transfer ? transfer + " " : "") + duration.padStart(8);
243
254
  const summaryWidth = Math.max(4, usable - prefixWidth - terminalCellWidth(suffix));
244
255
  const summaryLines = wrapText(item.summary || item.action || "Tool call", summaryWidth, 3);
245
256
 
@@ -464,6 +475,7 @@ export class RemoteTui {
464
475
  summary: message.summary || humanizeToolCall({ action: message.action }),
465
476
  status: "running",
466
477
  ok: null,
478
+ requestBytes: Number.isFinite(Number(message.requestBytes)) ? Number(message.requestBytes) : undefined,
467
479
  });
468
480
  } else if (message.event === "tool:end") {
469
481
  const item = [...this.transactions].reverse().find((entry) => entry.requestId === message.requestId);
@@ -471,26 +483,69 @@ export class RemoteTui {
471
483
  item.status = "done";
472
484
  item.ok = message.ok !== false;
473
485
  item.durationMs = message.durationMs;
486
+ if (Number.isFinite(Number(message.responseBytes))) item.responseBytes = Number(message.responseBytes);
474
487
  if (message.error && message.ok === false) item.summary += ` · ${truncate(message.error, 48)}`;
475
488
  }
476
489
  } 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
- });
490
+ const activity = message.activity && typeof message.activity === "object" ? message.activity : null;
491
+ if (activity) {
492
+ const tool = String(activity.tool || "learn");
493
+ const change = activity.change && typeof activity.change === "object" ? activity.change : null;
494
+ const scopeSummary = String(activity.scopeSummary || "").trim();
495
+ const kind = String(change?.kind || activity.kind || "memory").trim() || "memory";
496
+ const key = String(change?.key || "").trim();
497
+ const verbs = {
498
+ created: "created",
499
+ updated: "updated",
500
+ reinforced: "reinforced",
501
+ weakened: "weakened",
502
+ removed: "removed",
503
+ };
504
+ let detail;
505
+ if (tool === "learn_prepare") {
506
+ detail = "prepare " + (scopeSummary || "relevant") + " context";
507
+ } else if (tool === "learn_get") {
508
+ detail = "read " + (scopeSummary || "memory") + " context";
509
+ } else if (change) {
510
+ detail = (verbs[String(change.type || "")] || "updated") + " " + kind + (key ? " · " + key : "");
511
+ } else if (tool === "learn_put") {
512
+ detail = "write " + kind + " · no change";
513
+ } else if (tool === "learn_delete") {
514
+ detail = "delete memory · no change";
515
+ } else if (tool === "learn_feedback") {
516
+ detail = String(activity.feedback || "feedback") + " memory · no change";
517
+ } else {
518
+ detail = tool.replace(/^learn_/, "").replace(/_/g, " ");
519
+ }
520
+ const durationMs = Number(activity.durationMs);
521
+ this.appendTransaction({
522
+ requestId: String(activity.eventId || "learn-call-" + Date.now()),
523
+ at: activity.at || message.at || new Date().toISOString(),
524
+ action: tool,
525
+ summary: "🧠 Learn · " + truncate(detail, 120),
526
+ status: "done",
527
+ ok: activity.ok !== false,
528
+ ...(Number.isFinite(durationMs) ? { durationMs } : {}),
529
+ });
530
+ } else {
531
+ const change = message.change && typeof message.change === "object" ? message.change : {};
532
+ const marker = {
533
+ created: "+",
534
+ updated: "~",
535
+ reinforced: "^",
536
+ weakened: "v",
537
+ removed: "-",
538
+ }[String(change.type || "")] || "~";
539
+ const detail = String(change.summary || change.key || "Learn updated").replace(/\s+/g, " ").trim();
540
+ this.appendTransaction({
541
+ requestId: "learn-" + String(change.eventId || Date.now()),
542
+ at: change.at || message.at || new Date().toISOString(),
543
+ action: "learn",
544
+ summary: "Learn " + marker + " " + truncate(detail, 120),
545
+ status: "done",
546
+ ok: true,
547
+ });
548
+ }
494
549
  } else if (message.event === "system") {
495
550
  this.appendTransaction({
496
551
  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.2.0",
3
+ "version": "1.2.2",
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": {
@@ -40,11 +40,11 @@
40
40
  "test:oauth": "node test/oauth-smoke.mjs",
41
41
  "test:usage": "node test/usage-smoke.mjs",
42
42
  "test:usage-storage": "node test/usage-storage.test.mjs",
43
+ "test:no-quota": "node test/no-quota-regression.test.mjs",
43
44
  "test:admin-api": "node test/admin-api-smoke.mjs",
44
45
  "test:admin-auth": "node test/admin-auth-smoke.mjs",
45
46
  "test:dashboard": "node test/dashboard-smoke.mjs",
46
47
  "test:dashboard-timers": "node test/dashboard-timers.test.mjs",
47
- "test:quota": "node test/quota-smoke.mjs",
48
48
  "test:ops": "node test/ops-smoke.mjs",
49
49
  "test:desktop": "node test/mcp-desktop-smoke.mjs",
50
50
  "test:device-management": "node test/device-management-smoke.mjs",
@@ -55,10 +55,11 @@
55
55
  "test:self-update": "node --test test/self-update.test.mjs test/agent-lifecycle-upgrade.test.mjs",
56
56
  "test:budget": "node --test test/relay-health.test.mjs test/usage-budget.test.mjs",
57
57
  "test:soak": "node test/soak-smoke.mjs",
58
- "test:hardening": "npm run test:tui && npm run test:config-security && npm run test:self-update && npm run test:budget && node --test test/connection-generation.test.mjs && npm run test:agent-state && node test/heartbeat-ack-watchdog.test.mjs && npm run test:usage-storage && npm run test:learn && npm run test:learn-bootstrap && npm run test:soak",
58
+ "test:hardening": "npm run test:tui && npm run test:config-security && npm run test:self-update && npm run test:budget && npm run test:worker-hotpath && node --test test/connection-generation.test.mjs && npm run test:agent-state && node test/heartbeat-ack-watchdog.test.mjs && npm run test:no-quota && npm run test:usage-storage && npm run test:learn && npm run test:learn-bootstrap && npm run test:soak",
59
59
  "verify:review": "node scripts/verify-review-artifacts.mjs",
60
60
  "test:learn": "node test/learning-smoke.mjs",
61
- "test:learn-bootstrap": "node test/learning-bootstrap-smoke.mjs"
61
+ "test:learn-bootstrap": "node test/learning-bootstrap-smoke.mjs",
62
+ "test:worker-hotpath": "node --experimental-strip-types --test test/relay-result.test.mjs"
62
63
  },
63
64
  "dependencies": {
64
65
  "ws": "^8.22.0"