dsh-multigameassistant 2.0.2 → 2.0.4

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.
@@ -12,23 +12,29 @@ import {
12
12
  DEFAULT_COMPACTION_THRESHOLD,
13
13
  ErrorCode,
14
14
  INSTANCES_CAPABILITY,
15
+ MAX_MEMORY_TEXT,
15
16
  MAX_SKILL_NAME,
17
+ MEMORY_CAPABILITY,
18
+ MemoryEntry,
19
+ MemoryKind,
16
20
  PERMISSIONS_CAPABILITY,
17
21
  PERSONA_CAPABILITY,
18
22
  Persona,
19
23
  PersonaSettings,
20
24
  ProviderApi,
21
25
  QUESTIONS_CAPABILITY,
22
- QUIET,
23
26
  Requests,
24
27
  RpcError,
28
+ SHARED_MEMORY,
25
29
  SKILLS_CAPABILITY,
26
30
  SKILL_NAME,
27
31
  areaOf,
28
32
  classify,
29
33
  external_exports,
34
+ personaOf,
35
+ personaPrompt,
30
36
  threadsBetween
31
- } from "./chunk-QAP7IYBS.js";
37
+ } from "./chunk-SA72K6M2.js";
32
38
  import {
33
39
  __commonJS,
34
40
  __require,
@@ -2121,7 +2127,7 @@ var require_extension = __commonJS({
2121
2127
  if (dest[name] === void 0) dest[name] = [elem];
2122
2128
  else dest[name].push(elem);
2123
2129
  }
2124
- function parse(header) {
2130
+ function parse3(header) {
2125
2131
  const offers = /* @__PURE__ */ Object.create(null);
2126
2132
  let params = /* @__PURE__ */ Object.create(null);
2127
2133
  let mustUnescape = false;
@@ -2261,7 +2267,7 @@ var require_extension = __commonJS({
2261
2267
  }).join(", ");
2262
2268
  }).join(", ");
2263
2269
  }
2264
- module.exports = { format, parse };
2270
+ module.exports = { format, parse: parse3 };
2265
2271
  }
2266
2272
  });
2267
2273
 
@@ -2274,7 +2280,7 @@ var require_websocket = __commonJS({
2274
2280
  var http = __require("http");
2275
2281
  var net = __require("net");
2276
2282
  var tls = __require("tls");
2277
- var { randomBytes: randomBytes2, createHash } = __require("crypto");
2283
+ var { randomBytes: randomBytes3, createHash } = __require("crypto");
2278
2284
  var { Duplex, Readable } = __require("stream");
2279
2285
  var { URL: URL2 } = __require("url");
2280
2286
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -2295,7 +2301,7 @@ var require_websocket = __commonJS({
2295
2301
  var {
2296
2302
  EventTarget: { addEventListener, removeEventListener }
2297
2303
  } = require_event_target();
2298
- var { format, parse } = require_extension();
2304
+ var { format, parse: parse3 } = require_extension();
2299
2305
  var { toBuffer } = require_buffer_util();
2300
2306
  var kAborted = Symbol("kAborted");
2301
2307
  var protocolVersions = [8, 13];
@@ -2812,7 +2818,7 @@ var require_websocket = __commonJS({
2812
2818
  }
2813
2819
  }
2814
2820
  const defaultPort = isSecure ? 443 : 80;
2815
- const key = randomBytes2(16).toString("base64");
2821
+ const key = randomBytes3(16).toString("base64");
2816
2822
  const request = isSecure ? https.request : http.request;
2817
2823
  const protocolSet = /* @__PURE__ */ new Set();
2818
2824
  let perMessageDeflate;
@@ -2972,7 +2978,7 @@ var require_websocket = __commonJS({
2972
2978
  }
2973
2979
  let extensions;
2974
2980
  try {
2975
- extensions = parse(secWebSocketExtensions);
2981
+ extensions = parse3(secWebSocketExtensions);
2976
2982
  } catch (err) {
2977
2983
  const message = "Invalid Sec-WebSocket-Extensions header";
2978
2984
  abortHandshake(websocket, socket, message);
@@ -3264,7 +3270,7 @@ var require_subprotocol = __commonJS({
3264
3270
  "node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/subprotocol.js"(exports, module) {
3265
3271
  "use strict";
3266
3272
  var { tokenChars } = require_validation();
3267
- function parse(header) {
3273
+ function parse3(header) {
3268
3274
  const protocols = /* @__PURE__ */ new Set();
3269
3275
  let start = -1;
3270
3276
  let end = -1;
@@ -3300,7 +3306,7 @@ var require_subprotocol = __commonJS({
3300
3306
  protocols.add(protocol);
3301
3307
  return protocols;
3302
3308
  }
3303
- module.exports = { parse };
3309
+ module.exports = { parse: parse3 };
3304
3310
  }
3305
3311
  });
3306
3312
 
@@ -3707,8 +3713,8 @@ var require_websocket_server = __commonJS({
3707
3713
 
3708
3714
  // packages/gateway/lib/index.js
3709
3715
  import { execFile } from "node:child_process";
3710
- import { randomBytes } from "node:crypto";
3711
- import { existsSync, mkdirSync as mkdirSync5, readFileSync as readFileSync2, writeFileSync } from "node:fs";
3716
+ import { randomBytes as randomBytes2 } from "node:crypto";
3717
+ import { existsSync, mkdirSync as mkdirSync5, readFileSync as readFileSync3, writeFileSync } from "node:fs";
3712
3718
  import { dirname as dirname5, join as join7 } from "node:path";
3713
3719
  import { fileURLToPath } from "node:url";
3714
3720
  import { Service } from "@deepseek-ai/cordis";
@@ -4004,6 +4010,135 @@ function providersCapability(deps) {
4004
4010
  };
4005
4011
  }
4006
4012
 
4013
+ // packages/gateway/lib/about.js
4014
+ import { readFileSync } from "node:fs";
4015
+ var PLUGIN_PACKAGE = "dsh-multigameassistant";
4016
+ var RELEASES_URL = "https://api.github.com/repos/haaahhhis/MultiGameAssistant/releases?per_page=30";
4017
+ var NPM_URL = `https://registry.npmjs.org/${PLUGIN_PACKAGE}`;
4018
+ var TIMEOUT_MS = 15e3;
4019
+ var PLUGIN_ASSET = `${PLUGIN_PACKAGE}.tgz`;
4020
+ function pluginVersion(manifest = new URL("../package.json", import.meta.url)) {
4021
+ try {
4022
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
4023
+ if (pkg.name !== PLUGIN_PACKAGE || typeof pkg.version !== "string")
4024
+ return void 0;
4025
+ return pkg.version === "0.0.0-source" ? void 0 : pkg.version;
4026
+ } catch {
4027
+ return void 0;
4028
+ }
4029
+ }
4030
+ function compareVersions(a, b) {
4031
+ const parse3 = (v) => {
4032
+ const [main = "", pre] = v.replace(/^v/, "").split("+")[0].split(/-(.*)/s);
4033
+ return { main: main.split(".").map((n) => Number.parseInt(n, 10) || 0), pre: pre === void 0 || pre === "" ? [] : pre.split(".") };
4034
+ };
4035
+ const x = parse3(a);
4036
+ const y = parse3(b);
4037
+ for (let i = 0; i < Math.max(x.main.length, y.main.length, 3); i++) {
4038
+ const d = (x.main[i] ?? 0) - (y.main[i] ?? 0);
4039
+ if (d !== 0)
4040
+ return Math.sign(d);
4041
+ }
4042
+ if (x.pre.length === 0 || y.pre.length === 0)
4043
+ return Math.sign(y.pre.length - x.pre.length);
4044
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
4045
+ const p = x.pre[i];
4046
+ const q = y.pre[i];
4047
+ if (p === void 0 || q === void 0)
4048
+ return p === void 0 ? -1 : 1;
4049
+ const pn = /^\d+$/.test(p);
4050
+ const qn = /^\d+$/.test(q);
4051
+ if (pn && qn && Number(p) !== Number(q))
4052
+ return Math.sign(Number(p) - Number(q));
4053
+ if (pn !== qn)
4054
+ return pn ? -1 : 1;
4055
+ if (!pn && p !== q)
4056
+ return p < q ? -1 : 1;
4057
+ }
4058
+ return 0;
4059
+ }
4060
+ var MAX_NOTE = 8e3;
4061
+ var MAX_NOTES = 8;
4062
+ function cleanNotes(body) {
4063
+ const lines = String(body ?? "").replace(/\r\n/g, "\n").replace(/<!--[\s\S]*?-->/g, "").split("\n");
4064
+ const out = [];
4065
+ let skipping = false;
4066
+ for (const line2 of lines) {
4067
+ const heading = /^##\s+(.+?)\s*$/.exec(line2);
4068
+ if (heading !== null)
4069
+ skipping = /^(下载|Downloads?)$/i.test(heading[1]);
4070
+ if (!skipping)
4071
+ out.push(line2);
4072
+ }
4073
+ const text = out.join("\n").trim();
4074
+ return text.length > MAX_NOTE ? `${text.slice(0, MAX_NOTE)}
4075
+
4076
+ \u2026\u2026\uFF08\u66F4\u591A\u89C1\u53D1\u5E03\u9875\uFF09` : text;
4077
+ }
4078
+ function releaseNotes(releases, current, upTo) {
4079
+ const pre = current.includes("-");
4080
+ return releases.filter((r) => r.draft !== true && (pre || r.prerelease !== true) && typeof r.tag_name === "string").map((r) => ({ release: r, version: String(r.tag_name).replace(/^v/, "") })).filter((c) => compareVersions(c.version, current) > 0 && compareVersions(c.version, upTo) <= 0).sort((a, b) => compareVersions(b.version, a.version)).slice(0, MAX_NOTES).map(({ release, version }) => ({
4081
+ version,
4082
+ ...typeof release.name === "string" && release.name.trim() !== "" ? { title: release.name.trim() } : {},
4083
+ ...typeof release.published_at === "string" ? { publishedAt: release.published_at } : {},
4084
+ url: typeof release.html_url === "string" ? release.html_url : "",
4085
+ body: cleanNotes(release.body)
4086
+ }));
4087
+ }
4088
+ function newestRelease(releases, current) {
4089
+ const pre = current.includes("-");
4090
+ return releases.filter((r) => r.draft !== true && (pre || r.prerelease !== true) && typeof r.tag_name === "string" && Array.isArray(r.assets) && r.assets.some((a) => a.name === PLUGIN_ASSET)).map((r) => ({ version: String(r.tag_name).replace(/^v/, ""), prerelease: r.prerelease === true, notesUrl: typeof r.html_url === "string" ? r.html_url : "" })).filter((r) => compareVersions(r.version, current) > 0).sort((a, b) => compareVersions(b.version, a.version))[0];
4091
+ }
4092
+ function aboutCapability(deps = {}) {
4093
+ const version = deps.version ?? (() => pluginVersion());
4094
+ const get = async (url, call) => {
4095
+ const response = await (deps.fetch ?? fetch)(url, {
4096
+ // GitHub's API refuses a request without a User-Agent.
4097
+ headers: { Accept: "application/json", "User-Agent": PLUGIN_PACKAGE },
4098
+ signal: AbortSignal.any([call.signal, AbortSignal.timeout(TIMEOUT_MS)])
4099
+ });
4100
+ if (!response.ok)
4101
+ throw new Error(`${new URL(url).host} \u8FD4\u56DE ${response.status}`);
4102
+ return response.json();
4103
+ };
4104
+ const checkUpdate = async (call) => {
4105
+ const current = version();
4106
+ if (current === void 0)
4107
+ throw new RpcError(ErrorCode.InvalidRequest, "\u53EA\u6709 dsh \u63D2\u4EF6\u7248\u5728\u8FD9\u91CC\u68C0\u67E5\u66F4\u65B0");
4108
+ let releases;
4109
+ try {
4110
+ releases = await get(RELEASES_URL, call);
4111
+ } catch (error) {
4112
+ throw new RpcError(ErrorCode.HostError, `\u8FDE\u4E0D\u4E0A GitHub\uFF0C\u6CA1\u80FD\u68C0\u67E5\u66F4\u65B0\uFF08${error instanceof Error ? error.message : String(error)}\uFF09`);
4113
+ }
4114
+ const found = Array.isArray(releases) ? newestRelease(releases, current) : void 0;
4115
+ const checkedAt = (deps.now ?? Date.now)();
4116
+ if (found === void 0)
4117
+ return { current, checkedAt };
4118
+ let onNpm;
4119
+ try {
4120
+ const tags = (await get(NPM_URL, call))["dist-tags"] ?? {};
4121
+ const served = tags[found.prerelease ? "next" : "latest"];
4122
+ onNpm = typeof served === "string" && compareVersions(served, found.version) >= 0;
4123
+ } catch {
4124
+ onNpm = void 0;
4125
+ }
4126
+ const notes = releaseNotes(releases, current, found.version);
4127
+ return { current, latest: { ...found, ...onNpm === void 0 ? {} : { onNpm }, notes }, checkedAt };
4128
+ };
4129
+ return {
4130
+ id: "about",
4131
+ version: 1,
4132
+ methods: {
4133
+ "about/info": () => {
4134
+ const v = version();
4135
+ return v === void 0 ? { edition: "other" } : { edition: "plugin", version: v };
4136
+ },
4137
+ "about/checkUpdate": (_params, call) => checkUpdate(call)
4138
+ }
4139
+ };
4140
+ }
4141
+
4007
4142
  // packages/gateway/lib/approvals.js
4008
4143
  var ApprovalBroker = class {
4009
4144
  pending = /* @__PURE__ */ new Map();
@@ -4144,6 +4279,7 @@ function skillSaveTool(deps) {
4144
4279
  "\u628A\u521A\u505A\u6210\u7684\u4E00\u4EF6\u4E8B\u4FDD\u5B58\u6210\u6280\u80FD\uFF08SKILL.md\uFF09\uFF0C\u4E0B\u6B21\u540C\u6837\u7684\u8BF7\u6C42\u76F4\u63A5\u7167\u7740\u505A\uFF0C\u4E0D\u7528\u91CD\u65B0\u6478\u7D22\u3001\u5C11\u8C03\u7528\u6A21\u578B\u3002",
4145
4280
  "content \u5199\u6D53\u7F29\u540E\u7684\u505A\u6CD5\uFF1A\u4EC0\u4E48\u65F6\u5019\u7528\uFF1B\u4E00\u6B65\u4E00\u6B65\u7684\u64CD\u4F5C\uFF08\u7528\u5230\u7684\u5DE5\u5177\u3001\u547D\u4EE4\u3001\u8DEF\u5F84\u3001\u53C2\u6570\u7167\u5B9E\u5199\uFF09\uFF1B\u5224\u65AD\u6210\u529F\u7684\u65B9\u6CD5\uFF1B\u8E29\u8FC7\u7684\u5751\u548C\u6CE8\u610F\u4E8B\u9879\u3002\u4E0D\u5199\u8FD9\u6B21\u5BF9\u8BDD\u7684\u95F2\u804A\u548C\u5931\u8D25\u7684\u5C1D\u8BD5\u8FC7\u7A0B\uFF0C\u53EA\u5199\u6700\u540E\u8D70\u901A\u7684\u8DEF\u3002",
4146
4281
  "description \u4E00\u4E24\u53E5\u8BDD\u5199\u6E05\u695A\u300C\u505A\u4EC0\u4E48\u3001\u7528\u6237\u8BF4\u4EC0\u4E48\u65F6\u7528\u300D\uFF0Cagent \u9760\u5B83\u51B3\u5B9A\u4EC0\u4E48\u65F6\u5019\u8C03\u7528\u3002\u5DF2\u6709\u540C\u540D\u6280\u80FD\u65F6\u5148\u7528 replace=true \u624D\u4F1A\u8986\u76D6\u3002",
4282
+ "\u6280\u80FD\u53EA\u5199\u300C\u600E\u4E48\u505A\u300D\uFF1A\u7528\u6237\u7684\u504F\u597D\u3001\u79F0\u547C\u3001\u7EA6\u5B9A\uFF0C\u548C\u8FD9\u6B21\u505A\u4E86\u4EC0\u4E48\u3001\u5B9A\u4E86\u4EC0\u4E48\uFF0C\u4E0D\u5199\u6210\u6280\u80FD\uFF0C\u7528 memory_save \u8BB0\u8FDB\u957F\u671F\u8BB0\u5FC6\u3002",
4147
4283
  "\u4E00\u5B9A\u8981\u5206\u5230\u5BF9\u5E94\u7684\u6E38\u620F\u548C\u811A\u672C\uFF1A\u53EA\u6709\u7528\u67D0\u4E2A\u811A\u672C\u65F6\u624D\u7528\u5F97\u4E0A\u7684\uFF08\u5B83\u7684\u914D\u7F6E\u3001\u62A5\u9519\u3001\u65E5\u5FD7\uFF09\u586B scripts\uFF08\u811A\u672C id\uFF09\uFF1B\u548C\u6E38\u620F\u672C\u8EAB\u6709\u5173\u3001\u6362\u4E2A\u811A\u672C\u4E5F\u7528\u5F97\u4E0A\u7684\uFF08\u6E38\u620F\u91CC\u7684\u64CD\u4F5C\u3001\u754C\u9762\u3001\u6D3B\u52A8\u3001\u673A\u5236\uFF09\u586B games\uFF08\u6E38\u620F id\uFF0Cgame_list \u53EF\u67E5\uFF09\uFF0C\u4E0D\u586B scripts\u3002\u8FD9\u6837\u5B83\u53EA\u5728\u5904\u7406\u8FD9\u4E2A\u811A\u672C\u6216\u6E38\u620F\u65F6\u51FA\u73B0\uFF0C\u4E0D\u4F1A\u88AB\u62FF\u53BB\u7528\u5728\u522B\u7684\u811A\u672C\u3001\u522B\u7684\u6E38\u620F\u4E0A\uFF0C\u300C\u6280\u80FD\u300D\u9875\u4E5F\u6309\u6E38\u620F\u5F52\u597D\u7C7B\u3002\u548C\u54EA\u4E2A\u6E38\u620F\u90FD\u65E0\u5173\u7684\u901A\u7528\u505A\u6CD5\u4E24\u4E2A\u90FD\u4E0D\u586B\u3002"
4148
4284
  ].join(""),
4149
4285
  parameters: {
@@ -4443,11 +4579,11 @@ function skillFocusTool(scope) {
4443
4579
  throw new Error("\u53EA\u80FD\u5728\u4F1A\u8BDD\u91CC\u8BBE\u7F6E");
4444
4580
  const { scripts, games, add } = parsed.data;
4445
4581
  const focus = await scope.setFocus(exec.agent.session.id, { scripts: scripts ?? [], games: games ?? [] }, add === true ? "add" : "replace");
4446
- const own = scope.skillsFor(focus).filter((s) => s.owner !== void 0);
4582
+ const own2 = scope.skillsFor(focus).filter((s) => s.owner !== void 0);
4447
4583
  return {
4448
4584
  focus,
4449
- skills: own.map((s) => ({ name: s.name, description: s.description })),
4450
- note: own.length === 0 ? "\u8FD9\u4E9B\u811A\u672C\u548C\u6E38\u620F\u8FD8\u6CA1\u6709\u4E13\u5C5E\u6280\u80FD\uFF1B\u901A\u7528\u6280\u80FD\u7167\u5E38\u53EF\u7528\u3002" : "\u8FD9\u4E9B\u6280\u80FD\u73B0\u5728\u53EF\u4EE5\u7528 skill \u5DE5\u5177\u52A0\u8F7D\uFF1B\u6280\u80FD\u5217\u8868\u4F1A\u5728\u4E0B\u4E00\u6B65\u66F4\u65B0\u3002"
4585
+ skills: own2.map((s) => ({ name: s.name, description: s.description })),
4586
+ note: own2.length === 0 ? "\u8FD9\u4E9B\u811A\u672C\u548C\u6E38\u620F\u8FD8\u6CA1\u6709\u4E13\u5C5E\u6280\u80FD\uFF1B\u901A\u7528\u6280\u80FD\u7167\u5E38\u53EF\u7528\u3002" : "\u8FD9\u4E9B\u6280\u80FD\u73B0\u5728\u53EF\u4EE5\u7528 skill \u5DE5\u5177\u52A0\u8F7D\uFF1B\u6280\u80FD\u5217\u8868\u4F1A\u5728\u4E0B\u4E00\u6B65\u66F4\u65B0\u3002"
4451
4587
  };
4452
4588
  },
4453
4589
  presentCall: (args) => {
@@ -4461,14 +4597,6 @@ function skillFocusTool(scope) {
4461
4597
  // packages/gateway/lib/persona.js
4462
4598
  import { mkdir as mkdir2, readFile as readFile3, rename, writeFile as writeFile2 } from "node:fs/promises";
4463
4599
  import { join as join3 } from "node:path";
4464
- var STYLE_TEXT = {
4465
- default: "",
4466
- concise: "\u56DE\u7B54\u7B80\u77ED\u76F4\u63A5\uFF1A\u5148\u7ED9\u7ED3\u8BBA\uFF0C\u518D\u7ED9\u5FC5\u8981\u7684\u7EC6\u8282\uFF1B\u5C11\u5BD2\u6684\uFF0C\u4E0D\u7528\u8868\u60C5\u3002",
4467
- patient: "\u8010\u5FC3\u3001\u8BB2\u6E05\u695A\uFF1A\u6BCF\u4E00\u6B65\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u4E48\u505A\uFF0C\u7528\u5BF9\u65B9\u542C\u5F97\u61C2\u7684\u8BDD\uFF0C\u50CF\u6559\u4E00\u4E2A\u521A\u63A5\u89E6\u7684\u4EBA\u3002",
4468
- lively: "\u8BED\u6C14\u8F7B\u677E\u6D3B\u6CFC\uFF0C\u53EF\u4EE5\u7528\u4E00\u70B9\u8BED\u6C14\u8BCD\u548C\u8868\u60C5\uFF0C\u4F46\u4FE1\u606F\u8981\u51C6\u786E\u3001\u4E0D\u5570\u55E6\u3002",
4469
- buddy: "\u50CF\u4E00\u8D77\u73A9\u6E38\u620F\u7684\u8001\u670B\u53CB\u90A3\u6837\u8BF4\u8BDD\uFF1A\u719F\u6089\u6E38\u620F\u91CC\u7684\u8BF4\u6CD5\uFF0C\u53EF\u4EE5\u9002\u5F53\u5410\u69FD\u548C\u9F13\u52B1\uFF0C\u4F46\u4E0D\u5938\u5F20\u3001\u4E0D\u6CB9\u817B\u3002",
4470
- butler: "\u50CF\u4E00\u4F4D\u7A33\u91CD\u5468\u5230\u7684\u7BA1\u5BB6\uFF1A\u793C\u8C8C\u3001\u6761\u7406\u6E05\u695A\uFF0C\u4E3B\u52A8\u6C47\u62A5\u8FDB\u5EA6\u548C\u9700\u8981\u5BF9\u65B9\u51B3\u5B9A\u7684\u4E8B\u3002"
4471
- };
4472
4600
  var DEFAULT_PERSONA = { persona: { style: "default" }, agents: {} };
4473
4601
  var IDENTITY_PROMPT = [
4474
4602
  "# \u672C\u8F6F\u4EF6",
@@ -4480,28 +4608,15 @@ var IDENTITY_PROMPT = [
4480
4608
  "\u5BF9\u8BDD\u91CC\u8F83\u65E9\u63D0\u5230\u7684\u4E8B\uFF08\u5F85\u529E\u3001\u6CA1\u56DE\u7B54\u7684\u95EE\u9898\u3001\u811A\u672C\u548C\u6D41\u6C34\u7EBF\u7684\u72B6\u6001\u3001\u6D3B\u52A8\u4FE1\u606F\uFF09\u53EF\u80FD\u65E9\u5C31\u8FC7\u65F6\u4E86\uFF1A\u5148\u7528\u5DE5\u5177\u67E5\u73B0\u5728\u7684\u60C5\u51B5\u518D\u8BF4\uFF1B\u67E5\u4E0D\u5230\u53C8\u5FC5\u987B\u95EE\u65F6\uFF0C\u8BF4\u660E\u662F\u54EA\u5929\u7684\u4E8B\u3002\u4E0D\u8981\u628A\u65E9\u5C31\u8FC7\u53BB\u7684\u95EE\u9898\u5F53\u6210\u521A\u53D1\u751F\u7684\u6765\u8FFD\u95EE\u3002",
4481
4609
  "",
4482
4610
  "# \u6280\u80FD",
4483
- "\u6BCF\u4E2A\u811A\u672C\u3001\u6BCF\u4E2A\u6E38\u620F\u7684\u4E13\u5C5E\u6280\u80FD\u53EA\u7ED9\u6B63\u5728\u5904\u7406\u5B83\u7684\u4F1A\u8BDD\u7528\uFF1A\u5F00\u59CB\u64CD\u4F5C\u3001\u5206\u6790\u3001\u8BCA\u65AD\u6216\u7F16\u6392\u67D0\u4E2A\u811A\u672C\uFF0C\u6216\u67E5\u770B\u67D0\u4E2A\u6E38\u620F\u4E4B\u524D\uFF0C\u5148\u7528 skill_focus \u8BF4\u660E\u662F\u54EA\u4E2A\uFF08\u51E0\u4E2A\u4E00\u8D77\u5904\u7406\u5C31\u4E00\u8D77\u5199\uFF09\uFF0C\u5B83\u4EEC\u7684\u6280\u80FD\u624D\u4F1A\u51FA\u73B0\u5728\u6280\u80FD\u5217\u8868\u91CC\uFF1B\u6362\u5230\u522B\u7684\u811A\u672C\u6216\u6E38\u620F\u65F6\u518D\u8C03\u7528\u4E00\u6B21\u3002\u4E0D\u8981\u628A\u4E00\u4E2A\u811A\u672C\u6216\u6E38\u620F\u7684\u6280\u80FD\u5957\u7528\u5230\u53E6\u4E00\u4E2A\u4E0A\u3002"
4611
+ "\u6BCF\u4E2A\u811A\u672C\u3001\u6BCF\u4E2A\u6E38\u620F\u7684\u4E13\u5C5E\u6280\u80FD\u53EA\u7ED9\u6B63\u5728\u5904\u7406\u5B83\u7684\u4F1A\u8BDD\u7528\uFF1A\u5F00\u59CB\u64CD\u4F5C\u3001\u5206\u6790\u3001\u8BCA\u65AD\u6216\u7F16\u6392\u67D0\u4E2A\u811A\u672C\uFF0C\u6216\u67E5\u770B\u67D0\u4E2A\u6E38\u620F\u4E4B\u524D\uFF0C\u5148\u7528 skill_focus \u8BF4\u660E\u662F\u54EA\u4E2A\uFF08\u51E0\u4E2A\u4E00\u8D77\u5904\u7406\u5C31\u4E00\u8D77\u5199\uFF09\uFF0C\u5B83\u4EEC\u7684\u6280\u80FD\u624D\u4F1A\u51FA\u73B0\u5728\u6280\u80FD\u5217\u8868\u91CC\uFF1B\u6362\u5230\u522B\u7684\u811A\u672C\u6216\u6E38\u620F\u65F6\u518D\u8C03\u7528\u4E00\u6B21\u3002\u4E0D\u8981\u628A\u4E00\u4E2A\u811A\u672C\u6216\u6E38\u620F\u7684\u6280\u80FD\u5957\u7528\u5230\u53E6\u4E00\u4E2A\u4E0A\u3002",
4612
+ "",
4613
+ "# \u5148\u7528\u811A\u672C\uFF0C\u518D\u7528\u81EA\u5DF1\u7684\u80FD\u529B",
4614
+ "\u7528\u6237\u8981\u5728\u6E38\u620F\u91CC\u505A\u4E00\u4EF6\u4E8B\uFF08\u5237\u5173\u5361\u3001\u6E05\u4F53\u529B\u3001\u9886\u5956\u52B1\u548C\u90AE\u4EF6\u3001\u505A\u65E5\u5E38\u5468\u5E38\u3001\u6536\u57FA\u5EFA\u3001\u5151\u6362\u5546\u5E97\u3001\u6253\u6D3B\u52A8\u2026\u2026\uFF09\u65F6\uFF0C\u6309\u8FD9\u4E2A\u987A\u5E8F\uFF1A",
4615
+ "1. \u5148\u770B\u8FD9\u4E2A\u6E38\u620F\u4E0B\u88C5\u4E86\u54EA\u4E9B\u811A\u672C\uFF08script_list\uFF09\uFF0C\u518D\u770B\u5B83\u4EEC\u6709\u6CA1\u6709\u505A\u8FD9\u4EF6\u4E8B\u7684\u4EFB\u52A1\u6216\u9009\u9879\uFF08script_tasks\uFF1B\u8BF4\u4E0D\u6E05\u65F6\u770B\u811A\u672C\u7684\u6280\u80FD\u3001script_help\uFF09\u3002",
4616
+ "2. \u811A\u672C\u80FD\u505A\uFF0C\u5C31\u7528\u811A\u672C\u505A\uFF1A\u8FD0\u884C\u5B83\u5BF9\u5E94\u7684\u4EFB\u52A1\uFF08script_run\uFF0C\u9700\u8981\u65F6\u5148\u6539\u8FD9\u6B21\u8981\u7528\u7684\u914D\u7F6E\uFF09\u3002\u4E0D\u8981\u81EA\u5DF1\u622A\u56FE\u3001\u70B9\u5C4F\u5E55\u53BB\u505A\u811A\u672C\u80FD\u505A\u7684\u4E8B\u3002\u4F60\u81EA\u5DF1\u4E0D\u80FD\u8FD0\u884C\u811A\u672C\u7684\uFF0C\u4EA4\u7ED9\u80FD\u8FD0\u884C\u7684\u540C\u4E8B\uFF08\u300C\u811A\u672C\u300Dagent\uFF09\uFF0C\u628A\u8981\u8DD1\u54EA\u4E2A\u811A\u672C\u7684\u54EA\u4E2A\u4EFB\u52A1\u5199\u6E05\u695A\u3002",
4617
+ "3. \u53EA\u6709\u786E\u8BA4\u811A\u672C\u505A\u4E0D\u4E86\uFF0C\u624D\u7528\u4F60\u81EA\u5DF1\u7684\u80FD\u529B\uFF08\u622A\u56FE\u70B9\u51FB\u3001\u547D\u4EE4\u884C\uFF09\u53BB\u505A\uFF1A\u88C5\u7740\u7684\u811A\u672C\u90FD\u6CA1\u6709\u8FD9\u4E2A\u529F\u80FD\uFF1B\u6216\u8005\u811A\u672C\u8DD1\u4E86\u5931\u8D25\u3001\u4FEE\u4E0D\u597D\u3002\u52A8\u624B\u524D\u7528\u4E00\u53E5\u8BDD\u544A\u8BC9\u7528\u6237\u4E3A\u4EC0\u4E48\u4E0D\u7528\u811A\u672C\u3002",
4618
+ "4. \u6709\u80FD\u505A\u8FD9\u4EF6\u4E8B\u7684\u811A\u672C\u4F46\u8FD8\u6CA1\u88C5\uFF1A\u5148\u544A\u8BC9\u7528\u6237\u662F\u54EA\u4E2A\u811A\u672C\u3001\u95EE\u8981\u4E0D\u8981\u88C5\uFF0C\u4E0D\u8981\u4E0D\u95EE\u5C31\u81EA\u5DF1\u70B9\u3002"
4484
4619
  ].join("\n");
4485
- function personaOf(settings, agentId) {
4486
- const own = Object.entries(settings.agents[agentId] ?? {}).filter(([, value]) => value !== void 0);
4487
- return { ...settings.persona, ...Object.fromEntries(own) };
4488
- }
4489
- function personaPrompt(p) {
4490
- const lines = [];
4491
- if (p.name !== void 0 && p.name.trim() !== "")
4492
- lines.push(`\u4F60\u7684\u540D\u5B57\u662F\u300C${p.name.trim()}\u300D\uFF0C\u81EA\u79F0\u65F6\u7528\u8FD9\u4E2A\u540D\u5B57\u3002`);
4493
- if (p.callUser !== void 0 && p.callUser.trim() !== "")
4494
- lines.push(`\u79F0\u547C\u7528\u6237\u4E3A\u300C${p.callUser.trim()}\u300D\u3002`);
4495
- if (STYLE_TEXT[p.style] !== "")
4496
- lines.push(STYLE_TEXT[p.style]);
4497
- if (p.custom !== void 0 && p.custom.trim() !== "")
4498
- lines.push(`\u7528\u6237\u5BF9\u4F60\u8BF4\u8BDD\u65B9\u5F0F\u7684\u8981\u6C42\uFF1A${p.custom.trim()}`);
4499
- if (lines.length === 0)
4500
- return "";
4501
- lines.push(p.peerStyle === "same" ? "\u548C\u5176\u4ED6 agent \u8BF4\u8BDD\u65F6\u4E5F\u7528\u8FD9\u4E2A\u65B9\u5F0F\u3002" : "\u4E0A\u9762\u662F\u5BF9\u7528\u6237\u8BF4\u8BDD\u7684\u65B9\u5F0F\u3002\u548C\u5176\u4ED6 agent \u8BF4\u8BDD\uFF08agent_delegate\u3001agent_message\u3001\u4EA4\u56DE\u53BB\u7684\u7ED3\u8BBA\uFF09\u7528\u5E73\u5B9E\u7684\u8BDD\uFF0C\u76F4\u63A5\u8BF4\u4E8B\uFF0C\u4E0D\u7528\u4EBA\u8BBE\u548C\u79F0\u547C\uFF1A\u5B83\u4EEC\u8981\u8BFB\u7684\u662F\u5185\u5BB9\u3002");
4502
- lines.push(`\u8F6F\u4EF6\u7EA6\u5B9A\u7684\u56FA\u5B9A\u5199\u6CD5\uFF08\u6BD4\u5982\u300C${QUIET}\u300D\u8FD9\u4E00\u53E5\u3001\u7EBF\u7D22\u7F16\u53F7\u3001\u5DE5\u5177\u7684\u53C2\u6570\uFF09\u4E00\u5B57\u4E0D\u5DEE\u7167\u5199\uFF0C\u4E0D\u52A0\u8BED\u6C14\u8BCD\u548C\u8868\u60C5\u3002`);
4503
- return ["# \u56DE\u590D\u98CE\u683C", ...lines, "\u8FD9\u4E9B\u53EA\u5F71\u54CD\u4F60\u8BF4\u8BDD\u7684\u65B9\u5F0F\uFF0C\u4E0D\u6539\u53D8\u505A\u4E8B\u7684\u89C4\u5219\uFF1A\u786E\u8BA4\u3001\u5B89\u5168\u9650\u5236\u548C\u4E0D\u80FD\u505A\u7684\u4E8B\u90FD\u7167\u65E7\uFF1B\u5728\u98DE\u4E66\u91CC\u56DE\u590D\u4E5F\u4E00\u6837\u3002"].join("\n");
4504
- }
4505
4620
  function cleanFields(p) {
4506
4621
  return {
4507
4622
  ...p.style === void 0 ? {} : { style: p.style },
@@ -4513,7 +4628,7 @@ function cleanFields(p) {
4513
4628
  }
4514
4629
  function clean(settings) {
4515
4630
  const { name: _name, ...rest } = cleanFields(settings.persona);
4516
- const agents = Object.entries(settings.agents).map(([id, own]) => [id, cleanFields(own)]).filter(([, own]) => Object.keys(own).length > 0);
4631
+ const agents = Object.entries(settings.agents).map(([id, own2]) => [id, cleanFields(own2)]).filter(([, own2]) => Object.keys(own2).length > 0);
4517
4632
  return { persona: { ...rest, style: settings.persona.style }, agents: Object.fromEntries(agents) };
4518
4633
  }
4519
4634
  function parseFile(raw) {
@@ -4564,6 +4679,7 @@ var VISIBLE = /* @__PURE__ */ new Set(["user/message", "assistant/message", "too
4564
4679
  function timeFacts(count, eventAt) {
4565
4680
  let previous;
4566
4681
  let summaryAt;
4682
+ let summaryCovers;
4567
4683
  for (let seq = count - 1; seq >= 0 && seq >= count - SCAN_LIMIT; seq--) {
4568
4684
  const event = eventAt(seq);
4569
4685
  if (event === void 0)
@@ -4575,8 +4691,25 @@ function timeFacts(count, eventAt) {
4575
4691
  break;
4576
4692
  if (event.type === "compaction/summary")
4577
4693
  summaryAt ??= event.time;
4694
+ if (summaryCovers === void 0 && isSummary(event))
4695
+ summaryCovers = coverOf(event, eventAt);
4696
+ }
4697
+ return { ...previous === void 0 ? {} : { previous }, ...summaryAt === void 0 ? {} : { summaryAt }, ...summaryCovers === void 0 ? {} : { summaryCovers } };
4698
+ }
4699
+ var isSummary = (event) => event.type === "user/message" && typeof event.surfaceOp === "object" && event.surfaceOp !== null && (event.sourceEventSeqs?.length ?? 0) > 0;
4700
+ function coverOf(summary, eventAt, depth = 0) {
4701
+ let cover;
4702
+ const widen = (next) => {
4703
+ cover = cover === void 0 ? next : { from: Math.min(cover.from, next.from), to: Math.max(cover.to, next.to), firstSeq: Math.min(cover.firstSeq, next.firstSeq), lastSeq: Math.max(cover.lastSeq, next.lastSeq) };
4704
+ };
4705
+ for (const seq of summary.sourceEventSeqs ?? []) {
4706
+ const source = eventAt(seq);
4707
+ if (source === void 0)
4708
+ continue;
4709
+ const inner = depth < 8 && isSummary(source) ? coverOf(source, eventAt, depth + 1) : void 0;
4710
+ widen(inner ?? { from: source.time, to: source.time, firstSeq: seq, lastSeq: seq });
4578
4711
  }
4579
- return { ...previous === void 0 ? {} : { previous }, ...summaryAt === void 0 ? {} : { summaryAt } };
4712
+ return cover;
4580
4713
  }
4581
4714
  function timeNote(facts, now, step, timeZone) {
4582
4715
  const lines = [];
@@ -4584,7 +4717,9 @@ function timeNote(facts, now, step, timeZone) {
4584
4717
  lines.push(`\uFF08\u63D0\u9192\uFF09\u8DDD\u4E0A\u4E00\u6761\u6D88\u606F\u8FC7\u53BB\u4E86 ${formatGap(now - facts.previous)}\uFF08\u4E0A\u4E00\u6761\u5728 ${formatTime(facts.previous, timeZone)}\uFF0C\u73B0\u5728 ${formatTime(now, timeZone)}\uFF09\u3002\u4E4B\u524D\u5BF9\u8BDD\u91CC\u7684\u5F85\u529E\u3001\u95EE\u9898\u548C\u72B6\u6001\u53EF\u80FD\u5DF2\u7ECF\u8FC7\u65F6\uFF1A\u6D89\u53CA\u5B83\u4EEC\u65F6\u5148\u7528\u5DE5\u5177\u67E5\u73B0\u5728\u7684\u60C5\u51B5\uFF0C\u4E0D\u8981\u76F4\u63A5\u8FFD\u95EE\uFF1B\u8FD8\u9700\u8981\u95EE\u65F6\u8BF4\u660E\u662F\u54EA\u5929\u7684\u4E8B\u3002`);
4585
4718
  }
4586
4719
  if (facts.summaryAt !== void 0) {
4587
- lines.push(`\uFF08\u63D0\u9192\uFF09\u524D\u9762\u7684\u5BF9\u8BDD\u6458\u8981\u751F\u6210\u4E8E ${formatTime(facts.summaryAt, timeZone)}\uFF0C\u53EA\u53CD\u6620\u90A3\u65F6\u7684\u60C5\u51B5\uFF0C\u91CC\u9762\u7684\u5F85\u529E\u548C\u4E0B\u4E00\u6B65\u4EE5\u73B0\u5728\u7684\u5B9E\u9645\u72B6\u6001\u4E3A\u51C6\u3002`);
4720
+ const cover = facts.summaryCovers;
4721
+ const span = cover === void 0 ? "" : `\uFF0C\u6982\u62EC\u7684\u662F ${formatTime(cover.from, timeZone)} \u5230 ${formatTime(cover.to, timeZone)} \u7684\u5BF9\u8BDD\uFF08\u539F\u6587\u662F #${cover.firstSeq}\u2013#${cover.lastSeq}\uFF0C\u8981\u7EC6\u8282\u7528 history_read \u67E5\uFF09`;
4722
+ lines.push(`\uFF08\u63D0\u9192\uFF09\u524D\u9762\u7684\u5BF9\u8BDD\u6458\u8981\u751F\u6210\u4E8E ${formatTime(facts.summaryAt, timeZone)}${span}\uFF0C\u53EA\u53CD\u6620\u90A3\u65F6\u7684\u60C5\u51B5\uFF0C\u91CC\u9762\u7684\u5F85\u529E\u548C\u4E0B\u4E00\u6B65\u4EE5\u73B0\u5728\u7684\u5B9E\u9645\u72B6\u6001\u4E3A\u51C6\u3002`);
4588
4723
  }
4589
4724
  return lines.length === 0 ? void 0 : lines.join("\n");
4590
4725
  }
@@ -4661,11 +4796,11 @@ function compactOutcome(result) {
4661
4796
  }
4662
4797
 
4663
4798
  // packages/gateway/lib/compaction-settings.js
4664
- import { readFileSync } from "node:fs";
4799
+ import { readFileSync as readFileSync2 } from "node:fs";
4665
4800
  import { mkdir as mkdir3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
4666
4801
  import { join as join4 } from "node:path";
4667
4802
  var COMPACTION_FILE = "compaction.json";
4668
- var DEFAULT_COMPACTION = { auto: true, threshold: DEFAULT_COMPACTION_THRESHOLD };
4803
+ var DEFAULT_COMPACTION = { auto: true, threshold: DEFAULT_COMPACTION_THRESHOLD, lowContext: false };
4669
4804
  var CompactionStore = class {
4670
4805
  #file;
4671
4806
  /** As read at start: what dsh runs with. */
@@ -4677,21 +4812,21 @@ var CompactionStore = class {
4677
4812
  this.#current = this.applied;
4678
4813
  }
4679
4814
  state() {
4680
- return { settings: this.#current, applied: this.applied };
4815
+ return { settings: this.#current, applied: { ...this.applied, lowContext: this.#current.lowContext } };
4681
4816
  }
4682
4817
  async set(settings) {
4683
- const clean2 = CompactionSettings.parse(settings);
4818
+ const clean3 = CompactionSettings.parse(settings);
4684
4819
  await mkdir3(join4(this.#file, ".."), { recursive: true });
4685
- await writeFile3(`${this.#file}.tmp`, `${JSON.stringify(clean2, null, 2)}
4820
+ await writeFile3(`${this.#file}.tmp`, `${JSON.stringify(clean3, null, 2)}
4686
4821
  `);
4687
4822
  await rename2(`${this.#file}.tmp`, this.#file);
4688
- this.#current = clean2;
4823
+ this.#current = clean3;
4689
4824
  return this.state();
4690
4825
  }
4691
4826
  };
4692
4827
  function readSettings(file) {
4693
4828
  try {
4694
- const raw = JSON.parse(readFileSync(file, "utf8"));
4829
+ const raw = JSON.parse(readFileSync2(file, "utf8"));
4695
4830
  const parsed = CompactionSettings.safeParse({ ...DEFAULT_COMPACTION, ...raw });
4696
4831
  return parsed.success ? parsed.data : DEFAULT_COMPACTION;
4697
4832
  } catch {
@@ -4699,121 +4834,729 @@ function readSettings(file) {
4699
4834
  }
4700
4835
  }
4701
4836
 
4702
- // packages/gateway/lib/questions.js
4703
- var QuestionClosed = class extends Error {
4704
- outcome;
4705
- constructor(outcome) {
4706
- super(outcome === "cancelled" ? "the question was withdrawn" : "the question can no longer be answered");
4707
- this.outcome = outcome;
4837
+ // packages/gateway/lib/memory.js
4838
+ import { readFile as readFile4 } from "node:fs/promises";
4839
+ import { randomBytes } from "node:crypto";
4840
+ var PROMPT_PROFILE = 80;
4841
+ var PROMPT_PROFILE_CHARS = 8e3;
4842
+ var PROMPT_JOURNAL = 12;
4843
+ var PROMPT_JOURNAL_DAYS = 30;
4844
+ var MAX_ENTRIES = 2e3;
4845
+ function looksSecret(text) {
4846
+ if (/(密码|口令|验证码|动态码|password|passwd|passcode|pwd|token|api[\s_-]?key|secret|私钥|cookie)\s*(是|为|[::=])\s*\S{4,}/i.test(text))
4847
+ return true;
4848
+ if (/\b(sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|AKIA[0-9A-Z]{16}|xox[abpr]-[A-Za-z0-9-]{10,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})/.test(text))
4849
+ return true;
4850
+ for (const blob of text.match(/[A-Za-z0-9+/_=-]{32,}/g) ?? []) {
4851
+ if (/^[0-9a-f]+$/i.test(blob))
4852
+ continue;
4853
+ if (/[a-z]/.test(blob) && /[A-Z]/.test(blob) && /[0-9]/.test(blob))
4854
+ return true;
4708
4855
  }
4709
- };
4710
- var QuestionBroker = class {
4711
- pending = /* @__PURE__ */ new Map();
4712
- answerers = /* @__PURE__ */ new Set();
4713
- options;
4714
- constructor(options) {
4715
- this.options = options;
4856
+ return false;
4857
+ }
4858
+ var SECRET_REFUSAL = "\u8FD9\u6761\u50CF\u662F\u5BC6\u7801\u3001\u9A8C\u8BC1\u7801\u6216\u5BC6\u94A5\uFF1A\u8FD9\u7C7B\u4E1C\u897F\u4E0D\u5199\u8FDB\u8BB0\u5FC6\uFF08\u7528\u6237\u8BA9\u8BB0\u4E5F\u4E0D\u8BB0\uFF09\u3002\u628A\u5B83\u53BB\u6389\u518D\u8BB0\uFF0C\u6216\u8005\u544A\u8BC9\u7528\u6237\u4E3A\u4EC0\u4E48\u4E0D\u8BB0\u3002";
4859
+ var MemoryStore = class {
4860
+ #file;
4861
+ #changed;
4862
+ #items = [];
4863
+ loaded;
4864
+ constructor(file, changed) {
4865
+ this.#file = file;
4866
+ this.#changed = changed;
4867
+ this.loaded = this.#load();
4716
4868
  }
4717
- /** @returns a disposer. */
4718
- addAnswerer(answerer) {
4719
- this.answerers.add(answerer);
4720
- return () => {
4721
- this.answerers.delete(answerer);
4869
+ /** Every entry, newest first. */
4870
+ list() {
4871
+ return [...this.#items].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
4872
+ }
4873
+ /** What one agent reads: the shared entries and its own, newest first. */
4874
+ visibleTo(agentId) {
4875
+ return this.list().filter((entry) => entry.scope === SHARED_MEMORY || entry.scope === agentId);
4876
+ }
4877
+ get(id) {
4878
+ return this.#items.find((entry) => entry.id === id);
4879
+ }
4880
+ /** Write one; the same text already kept in the same place is touched, not written twice. */
4881
+ async add(write, now = /* @__PURE__ */ new Date()) {
4882
+ await this.loaded;
4883
+ const text = clean2(write.text);
4884
+ const same = this.#items.find((entry2) => entry2.kind === write.kind && entry2.scope === write.scope && entry2.text === text);
4885
+ if (same !== void 0)
4886
+ return this.update(same.id, { text }, write.by, now);
4887
+ const at = now.toISOString();
4888
+ const entry = { id: newId(now), kind: write.kind, scope: write.scope, text, createdAt: at, updatedAt: at, by: write.by };
4889
+ this.#items.push(entry);
4890
+ this.#trim();
4891
+ await this.#save();
4892
+ return entry;
4893
+ }
4894
+ async update(id, change, by, now = /* @__PURE__ */ new Date()) {
4895
+ await this.loaded;
4896
+ const index = this.#items.findIndex((entry2) => entry2.id === id);
4897
+ if (index < 0)
4898
+ throw new Error(`\u6CA1\u6709\u8FD9\u6761\u8BB0\u5FC6\uFF1A${id}`);
4899
+ const entry = {
4900
+ ...this.#items[index],
4901
+ text: clean2(change.text),
4902
+ ...change.kind === void 0 ? {} : { kind: change.kind },
4903
+ ...change.scope === void 0 ? {} : { scope: change.scope },
4904
+ updatedAt: now.toISOString(),
4905
+ by
4722
4906
  };
4907
+ this.#items[index] = entry;
4908
+ await this.#save();
4909
+ return entry;
4723
4910
  }
4724
- /** Whether some answerer besides protocol clients can take a question from `sessionId` now. */
4725
- hasActiveAnswerer(sessionId) {
4726
- for (const answerer of this.answerers)
4727
- if (safely2(() => answerer.active(sessionId), false))
4728
- return true;
4729
- return false;
4911
+ async remove(id) {
4912
+ await this.loaded;
4913
+ const before = this.#items.length;
4914
+ this.#items = this.#items.filter((entry) => entry.id !== id);
4915
+ if (this.#items.length === before)
4916
+ return false;
4917
+ await this.#save();
4918
+ return true;
4730
4919
  }
4731
4920
  /**
4732
- * Put the questions to the clients and answerers and wait for the first answer.
4733
- * @throws QuestionClosed when the agent stops waiting or the broker goes away.
4921
+ * Entries one agent reads that hold every word of the query (any case);
4922
+ * no words: the newest. Chinese has no spaces, so a word is a substring.
4734
4923
  */
4735
- ask(ask) {
4736
- if (ask.signal?.aborted === true)
4737
- return Promise.reject(new QuestionClosed("cancelled"));
4738
- const questionId = crypto.randomUUID();
4739
- const request = {
4740
- questionId,
4741
- sessionId: ask.sessionId,
4742
- ...ask.callId === void 0 ? {} : { callId: ask.callId },
4743
- questions: ask.questions.map((q) => ({
4744
- id: q.id,
4745
- question: q.question,
4746
- ...q.detail === void 0 ? {} : { detail: q.detail },
4747
- ...q.header === void 0 ? {} : { header: q.header },
4748
- ...q.options === void 0 ? {} : { options: q.options.map((o) => ({ label: o.label, ...o.description === void 0 ? {} : { description: o.description } })) },
4749
- ...q.multiSelect === void 0 ? {} : { multiSelect: q.multiSelect }
4750
- }))
4751
- };
4752
- return new Promise((resolve3, reject) => {
4753
- const onAbort = () => this.settle(questionId, "cancelled");
4754
- this.pending.set(questionId, {
4755
- request,
4756
- settle: (outcome, answer) => {
4757
- ask.signal?.removeEventListener("abort", onAbort);
4758
- if (outcome === "answered" && answer !== void 0)
4759
- resolve3(answer);
4760
- else
4761
- reject(new QuestionClosed(outcome === "answered" ? "unavailable" : outcome));
4762
- }
4924
+ search(agentId, query, options = {}) {
4925
+ const words = query.toLowerCase().split(/\s+/).filter((word) => word !== "");
4926
+ return this.visibleTo(agentId).filter((entry) => options.kind === void 0 || entry.kind === options.kind).filter((entry) => words.every((word) => entry.text.toLowerCase().includes(word))).slice(0, options.limit ?? 30);
4927
+ }
4928
+ /** Over the limit: the oldest journal entries go, then the oldest of all. */
4929
+ #trim() {
4930
+ while (this.#items.length > MAX_ENTRIES) {
4931
+ const oldest = (list) => list.reduce((a, b) => a.updatedAt <= b.updatedAt ? a : b);
4932
+ const journal = this.#items.filter((entry) => entry.kind === "journal");
4933
+ const drop = oldest(journal.length > 0 ? journal : this.#items);
4934
+ this.#items = this.#items.filter((entry) => entry !== drop);
4935
+ }
4936
+ }
4937
+ async #load() {
4938
+ if (this.#file === void 0)
4939
+ return;
4940
+ try {
4941
+ const saved = JSON.parse(await readFile4(this.#file, "utf8"));
4942
+ const items = Array.isArray(saved.items) ? saved.items : [];
4943
+ this.#items = items.flatMap((item) => {
4944
+ const parsed = MemoryEntry.safeParse(item);
4945
+ return parsed.success ? [parsed.data] : [];
4763
4946
  });
4764
- ask.signal?.addEventListener("abort", onAbort, { once: true });
4765
- this.options.broadcastRequested(request);
4766
- for (const answerer of this.answerers) {
4767
- if (!this.pending.has(questionId))
4768
- break;
4769
- if (safely2(() => answerer.active(request.sessionId), false))
4770
- safely2(() => answerer.asked(request), void 0);
4947
+ } catch {
4948
+ }
4949
+ }
4950
+ async #save() {
4951
+ if (this.#file !== void 0)
4952
+ await writeFileAtomic(this.#file, `${JSON.stringify({ version: 1, items: this.#items }, null, 1)}
4953
+ `);
4954
+ this.#changed?.();
4955
+ }
4956
+ };
4957
+ function clean2(text) {
4958
+ const trimmed = text.replace(/\s+/g, " ").trim();
4959
+ if (trimmed === "")
4960
+ throw new Error("\u8BB0\u5FC6\u4E0D\u80FD\u662F\u7A7A\u7684");
4961
+ if (trimmed.length > MAX_MEMORY_TEXT)
4962
+ throw new Error(`\u4E00\u6761\u8BB0\u5FC6\u6700\u591A ${MAX_MEMORY_TEXT} \u4E2A\u5B57\uFF1A\u53EA\u5199\u4E00\u4EF6\u4E8B\uFF0C\u62C6\u6210\u51E0\u6761\u8BB0`);
4963
+ if (looksSecret(trimmed))
4964
+ throw new Error(SECRET_REFUSAL);
4965
+ return trimmed;
4966
+ }
4967
+ function newId(now) {
4968
+ return `m${now.getTime().toString(36)}${randomBytes(2).toString("hex")}`;
4969
+ }
4970
+ function stamp(iso, timeZone) {
4971
+ const parts = Object.fromEntries(new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(new Date(iso)).map((p) => [p.type, p.value]));
4972
+ return `${parts["year"]}-${parts["month"]}-${parts["day"]} ${parts["hour"]}:${parts["minute"]}`;
4973
+ }
4974
+ function entryTime(entry, timeZone) {
4975
+ return entry.kind === "journal" ? `\u8BB0\u4E8E ${stamp(entry.createdAt, timeZone)}` : `\u66F4\u65B0\u4E8E ${stamp(entry.updatedAt, timeZone)}`;
4976
+ }
4977
+ var HOW_TO_WRITE = [
4978
+ "## \u4EC0\u4E48\u65F6\u5019\u8BB0\u3001\u600E\u4E48\u8BB0",
4979
+ "- \u7528\u6237\u8BF4\u8D77\u81EA\u5DF1\u7684\u4E8B\uFF08\u600E\u4E48\u79F0\u547C\u3001\u504F\u597D\u548C\u4E60\u60EF\u3001\u7528\u7684\u7535\u8111\u548C\u8BBE\u5907\u3001\u73A9\u54EA\u4E9B\u6E38\u620F\u548C\u8D26\u53F7\u60C5\u51B5\u3001\u5B9A\u4E0B\u7684\u5206\u5DE5\u548C\u89C4\u77E9\uFF09\u3001\u7EA0\u6B63\u4F60\u3001\u6216\u8005\u8BF4\u300C\u8BB0\u4F4F\u2026\u300D\u65F6\uFF0C\u9A6C\u4E0A\u7528 memory_save \u8BB0\u6210\u8D44\u6599\uFF08kind=profile\uFF09\u3002",
4980
+ "- \u4E00\u4EF6\u4E8B\u505A\u5B8C\u6216\u6709\u4E86\u7ED3\u8BBA\uFF08\u88C5\u597D\u6216\u66F4\u65B0\u4E86\u811A\u672C\u3001\u6539\u4E86\u6D41\u6C34\u7EBF\u6216\u5B9A\u65F6\u3001\u89E3\u51B3\u4E86\u4E00\u4E2A\u95EE\u9898\u3001\u7528\u6237\u505A\u4E86\u51B3\u5B9A\u6216\u62D2\u7EDD\u4E86\u4EC0\u4E48\uFF09\uFF0C\u8FD9\u4E00\u8F6E\u7ED3\u675F\u524D\u7528 memory_save \u8BB0\u4E00\u6761\u65E5\u8BB0\uFF08kind=journal\uFF09\uFF1A\u505A\u4E86\u4EC0\u4E48\u3001\u7ED3\u679C\u600E\u6837\u3001\u8FD8\u5269\u4EC0\u4E48\u6CA1\u505A\u3002\u4E0D\u8BB0\u8FC7\u7A0B\u548C\u95F2\u804A\uFF0C\u4E5F\u4E0D\u8BB0\u4E00\u773C\u5C31\u80FD\u4ECE\u8F6F\u4EF6\u91CC\u67E5\u5230\u7684\u72B6\u6001\u3002",
4981
+ "- \u4E00\u6761\u53EA\u5199\u4E00\u4EF6\u4E8B\uFF0C\u5199\u6210\u4EE5\u540E\u4E0D\u770B\u8FD9\u6B21\u5BF9\u8BDD\u4E5F\u770B\u5F97\u61C2\u7684\u4E00\u53E5\u8BDD\uFF1A\u54EA\u4E2A\u6E38\u620F\u3001\u54EA\u4E2A\u811A\u672C\u3001\u5177\u4F53\u7684\u540D\u5B57\u548C\u6570\u5B57\u7167\u5B9E\u5199\uFF1B\u300C\u4ECA\u5929\u300D\u300C\u660E\u5929\u300D\u300C\u4E0B\u5468\u300D\u6362\u6210\u5177\u4F53\u65E5\u671F\u3002",
4982
+ "- \u5148\u770B\u4E0A\u9762\u6709\u6CA1\u6709\u540C\u4E00\u4EF6\u4E8B\uFF1A\u6709\u5C31\u7528 replaces \u6539\u90A3\u4E00\u6761\uFF0C\u4E0D\u8981\u91CD\u590D\u8BB0\uFF1B\u8FC7\u65F6\u4E86\u6216\u8BB0\u9519\u4E86\u7528 memory_forget \u5220\u6389\u3002\u7528\u6237\u8BF4\u300C\u5FD8\u6389\u2026\u300D\u300C\u522B\u8BB0\u2026\u300D\u5C31\u5220\u3002",
4983
+ "- \u6240\u6709 agent \u90FD\u8BE5\u77E5\u9053\u7684\uFF08\u79F0\u547C\u3001\u504F\u597D\u3001\u8BBE\u5907\u548C\u4E60\u60EF\u3001\u5927\u5BB6\u90FD\u8981\u5B88\u7684\u7EA6\u5B9A\uFF09\u8BB0\u6210\u5171\u4EAB\uFF08shared=true\uFF09\uFF1B\u53EA\u548C\u4F60\u81EA\u5DF1\u7684\u5DE5\u4F5C\u6709\u5173\u7684\u8BB0\u6210\u4F60\u81EA\u5DF1\u7684\u3002",
4984
+ "- \u4E0D\u8BB0\u5BC6\u7801\u3001\u9A8C\u8BC1\u7801\u3001\u5BC6\u94A5\u3001token\u3001cookie\uFF0C\u7528\u6237\u8BA9\u8BB0\u4E5F\u4E0D\u8BB0\uFF0C\u544A\u8BC9\u7528\u6237\u4E3A\u4EC0\u4E48\u3002",
4985
+ "- \u8BB0\u5FC6\u548C\u6280\u80FD\u662F\u4E24\u56DE\u4E8B\uFF1A\u4E00\u4EF6\u4E8B\u4E00\u6B65\u6B65\u600E\u4E48\u505A\uFF0C\u5B58\u6210\u6280\u80FD\uFF08skill_save\uFF09\uFF1B\u7528\u6237\u662F\u8C01\u3001\u559C\u6B22\u4EC0\u4E48\u3001\u7EA6\u5B9A\u4E86\u4EC0\u4E48\u3001\u505A\u8FC7\u4EC0\u4E48\uFF0C\u8BB0\u8FDB\u8BB0\u5FC6\u3002",
4986
+ "- \u7528\u6237\u95EE\u4F60\u8BB0\u5F97\u4EC0\u4E48\uFF0C\u7167\u5B9E\u8BF4\uFF08\u6309\u9700\u7528 memory_search \u67E5\u5168\uFF09\uFF1B\u7528\u6237\u4E5F\u53EF\u4EE5\u5728\u300C\u8BBE\u7F6E \u2192 \u8BB0\u5FC6\u300D\u91CC\u770B\u3001\u6539\u3001\u5220\u3002"
4987
+ ].join("\n");
4988
+ var HISTORY = [
4989
+ "## \u4EE5\u524D\u7684\u5BF9\u8BDD",
4990
+ "\u5BF9\u8BDD\u8F83\u65E9\u7684\u90E8\u5206\u53EF\u80FD\u5DF2\u7ECF\u538B\u7F29\u6210\u4E86\u6458\u8981\uFF08\u6253\u5F00\u4E86\u4F4E\u4E0A\u4E0B\u6587\u6A21\u5F0F\u65F6\uFF0C\u53EA\u7559\u6700\u8FD1 12 \u5C0F\u65F6\u7684\u5BF9\u8BDD\uFF09\uFF0C\u66F4\u65E9\u7684\u5BF9\u8BDD\u4F60\u4E5F\u770B\u4E0D\u5230\u3002\u6458\u8981\u540E\u9762\u7684\u63D0\u9192\u5199\u7740\u5B83\u6982\u62EC\u7684\u662F\u54EA\u6BB5\u65F6\u95F4\u3001\u54EA\u4E9B #\u7F16\u53F7\u3002\u6458\u8981\u548C\u4E0A\u9762\u7684\u8BB0\u5FC6\u4E0D\u591F\u7528\u65F6\u2014\u2014\u8981\u7528\u6237\u7684\u539F\u8BDD\u3001\u5177\u4F53\u7684\u6570\u5B57\u548C\u540D\u5B57\u3001\u5F53\u65F6\u7684\u8F93\u51FA\u2014\u2014\u7528 history_search \u6309\u5173\u952E\u8BCD\u67E5\u4EE5\u524D\u7684\u5BF9\u8BDD\u539F\u6587\uFF0C\u518D\u7528 history_read \u6309 #\u7F16\u53F7\u8BFB\u90A3\u4E00\u6BB5\u7684\u524D\u540E\u6587\u3002\u4E0D\u8981\u51ED\u5370\u8C61\u731C\u4EE5\u524D\u8BF4\u8FC7\u4EC0\u4E48\u3002"
4991
+ ].join("\n");
4992
+ function memoryPrompt(entries, agentId, options = {}) {
4993
+ const now = options.now ?? /* @__PURE__ */ new Date();
4994
+ const where = (entry) => entry.scope === SHARED_MEMORY ? "\u5171\u4EAB" : entry.scope === agentId ? "\u4F60\u81EA\u5DF1\u7684" : entry.scope;
4995
+ const line2 = (entry) => `- [${entry.id}] (${entryTime(entry, options.timeZone)}\uFF0C${where(entry)}) ${entry.text}`;
4996
+ const profile = [];
4997
+ let chars = 0;
4998
+ const allProfile = entries.filter((entry) => entry.kind === "profile");
4999
+ for (const entry of allProfile) {
5000
+ const text = line2(entry);
5001
+ if (profile.length >= PROMPT_PROFILE || chars + text.length > PROMPT_PROFILE_CHARS)
5002
+ break;
5003
+ profile.push(text);
5004
+ chars += text.length;
5005
+ }
5006
+ const since = now.getTime() - PROMPT_JOURNAL_DAYS * 864e5;
5007
+ const allJournal = entries.filter((entry) => entry.kind === "journal");
5008
+ const journal = allJournal.filter((entry) => Date.parse(entry.updatedAt) >= since).slice(0, PROMPT_JOURNAL);
5009
+ const parts = [
5010
+ "# \u957F\u671F\u8BB0\u5FC6",
5011
+ entries.length === 0 ? "\u4F60\u8FD8\u6CA1\u6709\u5173\u4E8E\u7528\u6237\u7684\u8BB0\u5FC6\u3002\u4E0B\u9762\u5199\u4E86\u4EC0\u4E48\u65F6\u5019\u8BE5\u8BB0\u3002" : "\u4E0B\u9762\u662F\u4E4B\u524D\u7684\u5BF9\u8BDD\u91CC\u8BB0\u4E0B\u7684\u5173\u4E8E\u7528\u6237\u7684\u4E8B\uFF08\u300C\u5171\u4EAB\u300D\u7684\u6240\u6709 agent \u90FD\u770B\u5F97\u5230\uFF0C\u300C\u4F60\u81EA\u5DF1\u7684\u300D\u53EA\u6709\u4F60\u770B\u5F97\u5230\uFF09\u3002\u7167\u7740\u7528\uFF0C\u4E0D\u7528\u5411\u7528\u6237\u590D\u8FF0\uFF1B\u548C\u7528\u6237\u73B0\u5728\u8BF4\u7684\u4E0D\u4E00\u6837\u65F6\u4EE5\u73B0\u5728\u8BF4\u7684\u4E3A\u51C6\uFF0C\u5E76\u66F4\u65B0\u8BB0\u5FC6\u3002\u65B9\u62EC\u53F7\u91CC\u662F\u8FD9\u6761\u7684 id\uFF0C\u5706\u62EC\u53F7\u91CC\u662F\u5B83\u8BB0\u4E0B\u6216\u6700\u540E\u66F4\u65B0\u7684\u65F6\u95F4\uFF1A\u8BF4\u5230\u5B83\u65F6\u6309\u8FD9\u4E2A\u65F6\u95F4\u8BF4\uFF08\u300C11 \u6708 12 \u65E5\u8BB0\u7684\u300D\uFF09\uFF0C\u8D8A\u65E9\u7684\u8D8A\u53EF\u80FD\u5DF2\u7ECF\u8FC7\u65F6\u3002"
5012
+ ];
5013
+ if (profile.length > 0)
5014
+ parts.push(["## \u8D44\u6599", ...profile, ...allProfile.length > profile.length ? [`\uFF08\u8FD8\u6709 ${allProfile.length - profile.length} \u6761\u8F83\u65E9\u7684\u8D44\u6599\uFF0C\u7528 memory_search \u67E5\uFF09`] : []].join("\n"));
5015
+ if (journal.length > 0 || allJournal.length > 0) {
5016
+ parts.push(["## \u8FD1\u671F\u65E5\u8BB0", ...journal.length === 0 ? ["\uFF08\u6700\u8FD1\u6CA1\u6709\uFF09"] : journal.map(line2), ...allJournal.length > journal.length ? [`\uFF08\u66F4\u65E9\u7684 ${allJournal.length - journal.length} \u6761\u65E5\u8BB0\u4E0D\u5728\u8FD9\u91CC\uFF0C\u8981\u7528\u65F6\u7528 memory_search \u67E5\uFF09`] : []].join("\n"));
5017
+ }
5018
+ parts.push(HISTORY);
5019
+ parts.push(options.lead === void 0 ? HOW_TO_WRITE : `\u8FD9\u4E9B\u53EA\u4F9B\u53C2\u8003\uFF1A\u4F60\u662F\u5B50 agent\uFF0C\u4E0D\u5199\u8BB0\u5FC6\u3002\u53D1\u73B0\u503C\u5F97\u8BB0\u7684\uFF08\u7528\u6237\u7684\u504F\u597D\u3001\u505A\u6210\u7684\u4E8B\uFF09\uFF0C\u5199\u8FDB\u4EA4\u7ED9\u300C${options.lead}\u300D\u7684\u56DE\u590D\u91CC\uFF0C\u7531\u5B83\u53BB\u8BB0\u3002`);
5020
+ return parts.join("\n\n");
5021
+ }
5022
+ var SaveArgs = external_exports.object({
5023
+ text: external_exports.string(),
5024
+ kind: MemoryKind,
5025
+ shared: external_exports.boolean().nullish(),
5026
+ replaces: external_exports.string().nullish()
5027
+ });
5028
+ var ForgetArgs = external_exports.object({ id: external_exports.string().min(1) });
5029
+ var SearchArgs = external_exports.object({ query: external_exports.string().nullish(), kind: MemoryKind.nullish(), limit: external_exports.number().int().min(1).max(100).nullish() });
5030
+ function parse(schema, args) {
5031
+ const parsed = schema.safeParse(args ?? {});
5032
+ if (!parsed.success)
5033
+ throw new Error(`\u53C2\u6570\u65E0\u6548\uFF1A${parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"} ${i.message}`).join("; ")}`);
5034
+ return parsed.data;
5035
+ }
5036
+ var render = (_args, value) => [{ type: "text", text: JSON.stringify(value, null, 1) }];
5037
+ function caller(deps, exec) {
5038
+ const agent = exec.agent === void 0 ? void 0 : deps.agentOf(exec.agent.session.id);
5039
+ if (agent === void 0)
5040
+ throw new Error("\u53EA\u6709\u672C\u8F6F\u4EF6\u7684 agent \u80FD\u7528\u8BB0\u5FC6");
5041
+ return agent;
5042
+ }
5043
+ function own(deps, agent, id) {
5044
+ const entry = deps.store.get(id);
5045
+ if (entry === void 0 || entry.scope !== SHARED_MEMORY && entry.scope !== agent)
5046
+ throw new Error(`\u6CA1\u6709\u8FD9\u6761\u8BB0\u5FC6\uFF1A${id}\uFF08\u7528 memory_search \u67E5 id\uFF09`);
5047
+ return entry;
5048
+ }
5049
+ var brief = (entry, timeZone) => ({ id: entry.id, kind: entry.kind, shared: entry.scope === SHARED_MEMORY, time: entryTime(entry, timeZone), text: entry.text });
5050
+ function memoryTools(deps) {
5051
+ const save = {
5052
+ name: "memory_save",
5053
+ description: [
5054
+ "\u628A\u5173\u4E8E\u7528\u6237\u7684\u4E00\u4EF6\u4E8B\u8BB0\u8FDB\u957F\u671F\u8BB0\u5FC6\uFF0C\u4EE5\u540E\u7684\u65B0\u5BF9\u8BDD\u91CC\u4E5F\u8BB0\u5F97\u3002",
5055
+ "kind=profile\uFF08\u8D44\u6599\uFF09\uFF1A\u957F\u671F\u6709\u6548\u7684\u4E8B\u5B9E\u548C\u504F\u597D\u2014\u2014\u600E\u4E48\u79F0\u547C\u3001\u559C\u6B22\u600E\u6837\u3001\u8BBE\u5907\u548C\u73AF\u5883\u3001\u7EA6\u5B9A\u7684\u5206\u5DE5\u548C\u89C4\u77E9\uFF1Bkind=journal\uFF08\u65E5\u8BB0\uFF09\uFF1A\u54EA\u5929\u505A\u4E86\u4EC0\u4E48\u3001\u5B9A\u4E86\u4EC0\u4E48\u3001\u89E3\u51B3\u4E86\u4EC0\u4E48\u3001\u8FD8\u5269\u4EC0\u4E48\u3002",
5056
+ "\u4E00\u6761\u53EA\u5199\u4E00\u4EF6\u4E8B\uFF0C\u4E00\u53E5\u8BDD\u5199\u6E05\u695A\uFF0C\u65E5\u671F\u5199\u5177\u4F53\u7684\u3002shared=true \u6240\u6709 agent \u90FD\u80FD\u770B\u5230\uFF08\u504F\u597D\u3001\u79F0\u547C\u3001\u5927\u5BB6\u90FD\u8981\u5B88\u7684\u7EA6\u5B9A\uFF09\uFF0C\u5426\u5219\u53EA\u6709\u4F60\u81EA\u5DF1\u770B\u5230\u3002",
5057
+ "\u5DF2\u7ECF\u8BB0\u8FC7\u540C\u4E00\u4EF6\u4E8B\u5C31\u7528 replaces \u586B\u90A3\u6761\u7684 id \u6539\u5B83\uFF0C\u4E0D\u8981\u518D\u52A0\u4E00\u6761\u3002\u600E\u4E48\u505A\u4E00\u4EF6\u4E8B\u7684\u6B65\u9AA4\u4E0D\u8BB0\u5728\u8FD9\u91CC\uFF0C\u90A3\u662F\u6280\u80FD\uFF08skill_save\uFF09\u3002\u4E0D\u8BB0\u5BC6\u7801\u3001\u9A8C\u8BC1\u7801\u3001\u5BC6\u94A5\u3002"
5058
+ ].join(""),
5059
+ parameters: {
5060
+ type: "object",
5061
+ properties: {
5062
+ text: { type: "string", description: `\u8FD9\u6761\u8BB0\u5FC6\uFF0C\u4E00\u53E5\u8BDD\uFF08\u6700\u591A ${MAX_MEMORY_TEXT} \u5B57\uFF09\u3002` },
5063
+ kind: { type: "string", enum: ["profile", "journal"], description: "profile\uFF1A\u8D44\u6599\uFF08\u957F\u671F\u4E8B\u5B9E\u3001\u504F\u597D\u3001\u7EA6\u5B9A\uFF09\uFF1Bjournal\uFF1A\u65E5\u8BB0\uFF08\u505A\u8FC7\u3001\u5B9A\u8FC7\u7684\u4E8B\uFF09\u3002" },
5064
+ shared: { type: "boolean", description: "\u6240\u6709 agent \u90FD\u80FD\u770B\u5230\uFF08\u53EF\u9009\uFF0C\u9ED8\u8BA4\u53EA\u6709\u4F60\u81EA\u5DF1\uFF09\u3002" },
5065
+ replaces: { type: "string", description: "\u8981\u6539\u7684\u90A3\u6761\u8BB0\u5FC6\u7684 id\uFF08\u53EF\u9009\uFF09\u3002" }
5066
+ },
5067
+ required: ["text", "kind"],
5068
+ additionalProperties: false
5069
+ },
5070
+ output: { schema: {}, render },
5071
+ timeoutMs: 1e4,
5072
+ isConcurrencySafe: () => false,
5073
+ execute: async (args, exec) => {
5074
+ const agent = caller(deps, exec);
5075
+ const { text, kind, shared, replaces } = parse(SaveArgs, args);
5076
+ if (replaces != null && replaces !== "") {
5077
+ const old = own(deps, agent, replaces);
5078
+ const scope = shared == null ? old.scope : shared ? SHARED_MEMORY : agent;
5079
+ const entry2 = await deps.store.update(old.id, { text, kind, scope }, agent);
5080
+ return { saved: brief(entry2, deps.timeZone), replaced: old.text };
5081
+ }
5082
+ const entry = await deps.store.add({ kind, scope: shared === true ? SHARED_MEMORY : agent, text, by: agent });
5083
+ return { saved: brief(entry, deps.timeZone), note: "\u5DF2\u8BB0\u4E0B\uFF0C\u4EE5\u540E\u7684\u5BF9\u8BDD\u91CC\u90FD\u8BB0\u5F97" };
5084
+ },
5085
+ presentCall: (args) => {
5086
+ const a = args ?? {};
5087
+ return { card: "generic", title: `${a.kind === "journal" ? "\u8BB0\u65E5\u8BB0" : "\u8BB0\u4F4F"}\uFF1A${String(a.text ?? "").slice(0, 60)}`, kind: "other" };
5088
+ }
5089
+ };
5090
+ const forget = {
5091
+ name: "memory_forget",
5092
+ description: "\u4ECE\u957F\u671F\u8BB0\u5FC6\u91CC\u5220\u6389\u4E00\u6761\uFF08\u8FC7\u65F6\u4E86\u3001\u8BB0\u9519\u4E86\u3001\u7528\u6237\u8BF4\u300C\u5FD8\u6389\u300D\uFF09\u3002id \u5728\u7CFB\u7EDF\u63D0\u793A\u7684\u8BB0\u5FC6\u91CC\u6216\u7528 memory_search \u67E5\u3002",
5093
+ parameters: { type: "object", properties: { id: { type: "string", description: "\u8BB0\u5FC6\u7684 id\u3002" } }, required: ["id"], additionalProperties: false },
5094
+ output: { schema: {}, render },
5095
+ timeoutMs: 1e4,
5096
+ isConcurrencySafe: () => false,
5097
+ execute: async (args, exec) => {
5098
+ const agent = caller(deps, exec);
5099
+ const entry = own(deps, agent, parse(ForgetArgs, args).id);
5100
+ await deps.store.remove(entry.id);
5101
+ return { forgot: brief(entry, deps.timeZone) };
5102
+ },
5103
+ presentCall: () => ({ card: "generic", title: "\u5FD8\u6389\u4E00\u6761\u8BB0\u5FC6", kind: "other" })
5104
+ };
5105
+ const search = {
5106
+ name: "memory_search",
5107
+ description: "\u67E5\u957F\u671F\u8BB0\u5FC6\uFF08\u5171\u4EAB\u7684\u548C\u4F60\u81EA\u5DF1\u7684\uFF09\uFF0C\u5305\u62EC\u7CFB\u7EDF\u63D0\u793A\u91CC\u6CA1\u653E\u4E0B\u7684\u8F83\u65E9\u65E5\u8BB0\u3002query \u5199\u51E0\u4E2A\u5173\u952E\u8BCD\uFF08\u7A7A\u683C\u5206\u5F00\uFF0C\u5168\u90E8\u5305\u542B\u624D\u7B97\uFF09\uFF1B\u4E0D\u5199\u5C31\u5217\u51FA\u6700\u65B0\u7684\u3002\u7528\u6237\u95EE\u300C\u4E4B\u524D\u2026\u300D\u300C\u4E0A\u6B21\u2026\u300D\u300C\u6211\u8BF4\u8FC7\u2026\u300D\u65F6\u5148\u67E5\u8FD9\u91CC\u3002",
5108
+ parameters: {
5109
+ type: "object",
5110
+ properties: {
5111
+ query: { type: "string", description: "\u5173\u952E\u8BCD\uFF0C\u7A7A\u683C\u5206\u5F00\uFF08\u53EF\u9009\uFF09\u3002" },
5112
+ kind: { type: "string", enum: ["profile", "journal"], description: "\u53EA\u67E5\u8D44\u6599\u6216\u53EA\u67E5\u65E5\u8BB0\uFF08\u53EF\u9009\uFF09\u3002" },
5113
+ limit: { type: "number", description: "\u6700\u591A\u51E0\u6761\uFF08\u9ED8\u8BA4 30\uFF09\u3002" }
5114
+ },
5115
+ additionalProperties: false
5116
+ },
5117
+ output: { schema: {}, render },
5118
+ timeoutMs: 1e4,
5119
+ isConcurrencySafe: () => true,
5120
+ execute: async (args, exec) => {
5121
+ const agent = caller(deps, exec);
5122
+ const { query, kind, limit } = parse(SearchArgs, args);
5123
+ await deps.store.loaded;
5124
+ const found = deps.store.search(agent, query ?? "", { ...kind == null ? {} : { kind }, ...limit == null ? {} : { limit } });
5125
+ return { items: found.map((entry) => brief(entry, deps.timeZone)), ...found.length === 0 ? { note: "\u6CA1\u6709\u627E\u5230\u3002\u6362\u4E2A\u8BF4\u6CD5\u518D\u67E5\uFF0C\u6216\u8005\u5C31\u662F\u6CA1\u8BB0\u8FC7\u3002" } : {} };
5126
+ },
5127
+ presentCall: (args) => ({ card: "generic", title: `\u67E5\u8BB0\u5FC6\uFF1A${String(args?.query ?? "\u6700\u65B0\u7684")}`, kind: "other" })
5128
+ };
5129
+ return [save, forget, search];
5130
+ }
5131
+
5132
+ // packages/gateway/lib/memory-auto.js
5133
+ import { readFile as readFile5 } from "node:fs/promises";
5134
+ var AUTO_AUTHOR = "auto";
5135
+ var DEFAULT_IDLE_MS = 5 * 6e4;
5136
+ var MAX_CHARS = 14e3;
5137
+ var MAX_MESSAGE_CHARS = 2e3;
5138
+ var MAX_OPS = 6;
5139
+ var MAX_CURSORS = 2e3;
5140
+ var DEFAULT_AUTO_SETTINGS = { auto: true, model: null };
5141
+ var textOf = (content) => content.map((p) => p.type === "text" ? p.text ?? "" : "").join("").trim();
5142
+ function exchangesOf(events, after) {
5143
+ const out = [];
5144
+ for (const event of events) {
5145
+ if (event.seq <= after)
5146
+ continue;
5147
+ if (event.type === "user/message") {
5148
+ const text = textOf(event.content);
5149
+ if (text !== "")
5150
+ out.push({ seq: event.seq, time: event.time, from: event.origin.human ? "user" : "app", text });
5151
+ } else if (event.type === "assistant/message") {
5152
+ const text = textOf(event.content);
5153
+ if (text !== "")
5154
+ out.push({ seq: event.seq, time: event.time, from: "agent", text });
5155
+ }
5156
+ }
5157
+ return out;
5158
+ }
5159
+ function fit(exchanges) {
5160
+ const kept = [];
5161
+ let total = 0;
5162
+ for (let i = exchanges.length - 1; i >= 0; i--) {
5163
+ const e = exchanges[i];
5164
+ const text = e.text.length > MAX_MESSAGE_CHARS ? `${e.text.slice(0, MAX_MESSAGE_CHARS)}\u2026\uFF08\u540E\u9762\u7701\u7565\uFF09` : e.text;
5165
+ if (total + text.length > MAX_CHARS && kept.length > 0)
5166
+ break;
5167
+ kept.unshift({ ...e, text });
5168
+ total += text.length;
5169
+ }
5170
+ return kept;
5171
+ }
5172
+ function day(time, timeZone) {
5173
+ return new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date(time));
5174
+ }
5175
+ function extractionSystem(agentName, today) {
5176
+ return [
5177
+ `\u4F60\u5728\u4E3A MultiGameAssistant\uFF08\u591A\u6E38\u620F\u52A9\u624B\uFF0C\u5E2E\u7528\u6237\u5B89\u88C5\u3001\u8C03\u5EA6\u548C\u770B\u62A4\u5404\u6E38\u620F\u7684\u65E5\u5E38\u811A\u672C\uFF09\u6574\u7406\u957F\u671F\u8BB0\u5FC6\u3002\u4E0B\u9762\u662F agent\u300C${agentName}\u300D\u6700\u8FD1\u7684\u4E00\u6BB5\u5BF9\u8BDD\u548C\u5DF2\u7ECF\u8BB0\u4E0B\u7684\u8BB0\u5FC6\u3002\u627E\u51FA\u503C\u5F97\u957F\u671F\u8BB0\u4F4F\u3001\u4F46\u8FD8\u6CA1\u8BB0\u4E0B\u7684\u4E8B\u3002\u4ECA\u5929\u662F ${today}\u3002`,
5178
+ "",
5179
+ '\u53EA\u8F93\u51FA\u4E00\u4E2A JSON \u5BF9\u8C61\uFF0C\u4E0D\u8981\u522B\u7684\u6587\u5B57\uFF1A{"ops":[...]}\uFF1B\u6CA1\u6709\u8981\u8BB0\u7684\u5C31\u8F93\u51FA {"ops":[]}\u3002\u6BCF\u4E2A op \u662F\u4E0B\u9762\u4E00\u79CD\uFF1A',
5180
+ '- {"op":"add","kind":"profile","shared":true,"text":"\u2026"}\uFF1A\u8D44\u6599\uFF0C\u957F\u671F\u6709\u6548\u7684\u4E8B\u5B9E\u548C\u504F\u597D',
5181
+ '- {"op":"add","kind":"journal","shared":true,"text":"\u2026"}\uFF1A\u65E5\u8BB0\uFF0C\u505A\u8FC7\u3001\u5B9A\u8FC7\u7684\u4E8B',
5182
+ '- {"op":"replace","id":"\u5DF2\u6709\u8BB0\u5FC6\u7684 id","text":"\u2026"}\uFF1A\u5DF2\u6709\u7684\u90A3\u6761\u8FC7\u65F6\u4E86\u6216\u4E0D\u51C6\u4E86\uFF0C\u6539\u6210\u73B0\u5728\u7684\u8BF4\u6CD5',
5183
+ "",
5184
+ "\u89C4\u5219\uFF1A",
5185
+ "- \u8D44\u6599\u53EA\u6765\u81EA\u3010\u7528\u6237\u3011\u4EB2\u53E3\u8BF4\u7684\u8BDD\uFF1A\u600E\u4E48\u79F0\u547C\u3001\u504F\u597D\u548C\u4E60\u60EF\u3001\u7535\u8111\u8BBE\u5907\u548C\u73AF\u5883\u3001\u73A9\u54EA\u4E9B\u6E38\u620F\u548C\u54EA\u4E2A\u670D\u3001\u5B9A\u4E0B\u7684\u89C4\u77E9\u548C\u5206\u5DE5\u3001\u5BF9 agent \u7684\u7EA0\u6B63\u548C\u8981\u6C42\u3002agent \u7684\u731C\u6D4B\u548C\u3010\u8F6F\u4EF6\u3011\u7684\u6D88\u606F\u4E0D\u7B97\u8D44\u6599\u3002",
5186
+ "- \u65E5\u8BB0\u8BB0\u7ED3\u679C\uFF1A\u88C5\u597D\u6216\u66F4\u65B0\u4E86\u4EC0\u4E48\u3001\u6539\u4E86\u54EA\u6761\u6D41\u6C34\u7EBF\u6216\u5B9A\u65F6\u3001\u89E3\u51B3\u4E86\u4EC0\u4E48\u95EE\u9898\u3001\u7528\u6237\u51B3\u5B9A\u4E86\u4EC0\u4E48\u6216\u62D2\u7EDD\u4E86\u4EC0\u4E48\u3001\u8FD8\u6709\u4EC0\u4E48\u6CA1\u505A\u5B8C\u3002\u5199\u5177\u4F53\u65E5\u671F\uFF0C\u4E0D\u5199\u300C\u4ECA\u5929\u300D\u300C\u660E\u5929\u300D\u3002\u4E0D\u8BB0\u95F2\u804A\u3001\u505A\u5230\u4E00\u534A\u7684\u8FC7\u7A0B\u3001\u5931\u8D25\u7684\u5C1D\u8BD5\uFF0C\u4E5F\u4E0D\u8BB0\u968F\u65F6\u80FD\u5728\u8F6F\u4EF6\u91CC\u67E5\u5230\u7684\u72B6\u6001\uFF08\u811A\u672C\u5217\u8868\u3001\u8FD0\u884C\u8BB0\u5F55\u3001\u6D3B\u52A8\u65E5\u5386\uFF09\u3002",
5187
+ "- \u5DF2\u6709\u8BB0\u5FC6\u91CC\u8BF4\u8FC7\u7684\u4E0D\u8981\u518D\u8BB0\uFF1B\u540C\u4E00\u4EF6\u4E8B\u8BF4\u6CD5\u53D8\u4E86\uFF0C\u7528 replace \u6539\u90A3\u4E00\u6761\u3002",
5188
+ "- \u4E00\u6761\u53EA\u5199\u4E00\u4EF6\u4E8B\uFF0C\u4E00\u53E5\u8BDD\uFF0C\u4E0D\u770B\u8FD9\u6BB5\u5BF9\u8BDD\u4E5F\u8BFB\u5F97\u61C2\uFF1A\u5199\u6E05\u695A\u662F\u54EA\u4E2A\u6E38\u620F\u3001\u54EA\u4E2A\u811A\u672C\u3001\u5177\u4F53\u7684\u540D\u5B57\u548C\u6570\u5B57\u3002",
5189
+ `- shared\uFF1A\u6240\u6709 agent \u90FD\u8BE5\u77E5\u9053\u7684\uFF08\u79F0\u547C\u3001\u504F\u597D\u3001\u8BBE\u5907\u3001\u901A\u7528\u7684\u7EA6\u5B9A\u3001\u91CD\u8981\u7684\u4E8B\uFF09\u4E3A true\uFF1B\u53EA\u548C\u300C${agentName}\u300D\u81EA\u5DF1\u7684\u5DE5\u4F5C\u6709\u5173\u7684\u4E3A false\u3002`,
5190
+ "- \u7EDD\u5BF9\u4E0D\u8BB0\u5BC6\u7801\u3001\u9A8C\u8BC1\u7801\u3001\u5BC6\u94A5\u3001token\u3001cookie \u548C\u8D26\u53F7\u7684\u767B\u5F55\u4FE1\u606F\u3002",
5191
+ `- \u5B81\u7F3A\u6BCB\u6EE5\uFF1A\u62FF\u4E0D\u51C6\u5C31\u4E0D\u8BB0\u3002\u6700\u591A ${MAX_OPS} \u6761\u3002`
5192
+ ].join("\n");
5193
+ }
5194
+ function extractionPrompt(memories, exchanges, agentId, timeZone) {
5195
+ const where = (e) => e.scope === SHARED_MEMORY ? "\u5171\u4EAB" : e.scope === agentId ? "\u8FD9\u4E2A agent \u81EA\u5DF1\u7684" : e.scope;
5196
+ const kept = memories.length === 0 ? "\uFF08\u8FD8\u6CA1\u6709\uFF09" : memories.map((e) => `- [${e.id}] (${e.kind === "profile" ? "\u8D44\u6599" : "\u65E5\u8BB0"}\uFF0C${where(e)}\uFF0C${day(e.kind === "journal" ? e.createdAt : e.updatedAt, timeZone)}) ${e.text}`).join("\n");
5197
+ const who = { user: "\u7528\u6237", app: "\u8F6F\u4EF6", agent: "agent" };
5198
+ const talk = fit(exchanges).map((e) => `\u3010${who[e.from]}\u3011(${day(e.time, timeZone)}) ${e.text}`).join("\n\n");
5199
+ return `# \u5DF2\u6709\u7684\u8BB0\u5FC6
5200
+ ${kept}
5201
+
5202
+ # \u6700\u8FD1\u7684\u5BF9\u8BDD
5203
+ ${talk}`;
5204
+ }
5205
+ var Op = external_exports.discriminatedUnion("op", [
5206
+ external_exports.object({ op: external_exports.literal("add"), kind: external_exports.enum(["profile", "journal"]), shared: external_exports.boolean().optional(), text: external_exports.string().min(1) }),
5207
+ external_exports.object({ op: external_exports.literal("replace"), id: external_exports.string().min(1), text: external_exports.string().min(1) })
5208
+ ]);
5209
+ function parseOps(answer) {
5210
+ const body = answer.replace(/^[\s\S]*?```(?:json)?\s*([\s\S]*?)```[\s\S]*$/, "$1");
5211
+ const start = body.indexOf("{");
5212
+ const end = body.lastIndexOf("}");
5213
+ if (start < 0 || end < start)
5214
+ return [];
5215
+ let value;
5216
+ try {
5217
+ value = JSON.parse(body.slice(start, end + 1));
5218
+ } catch {
5219
+ return [];
5220
+ }
5221
+ const ops = value?.ops;
5222
+ if (!Array.isArray(ops))
5223
+ return [];
5224
+ return ops.flatMap((op) => {
5225
+ const parsed = Op.safeParse(op);
5226
+ return parsed.success ? [parsed.data] : [];
5227
+ }).slice(0, MAX_OPS);
5228
+ }
5229
+ async function applyOps(store, ops, agentId) {
5230
+ let added = 0;
5231
+ let replaced = 0;
5232
+ let skipped = 0;
5233
+ for (const op of ops) {
5234
+ try {
5235
+ if (op.op === "add") {
5236
+ await store.add({ kind: op.kind, scope: op.shared === false ? agentId : SHARED_MEMORY, text: op.text, by: AUTO_AUTHOR });
5237
+ added++;
5238
+ } else {
5239
+ const entry = store.get(op.id);
5240
+ if (entry === void 0 || entry.scope !== SHARED_MEMORY && entry.scope !== agentId) {
5241
+ skipped++;
5242
+ continue;
5243
+ }
5244
+ if (entry.text === op.text.replace(/\s+/g, " ").trim())
5245
+ continue;
5246
+ await store.update(entry.id, { text: op.text }, AUTO_AUTHOR);
5247
+ replaced++;
4771
5248
  }
5249
+ } catch {
5250
+ skipped++;
5251
+ }
5252
+ }
5253
+ return { added, replaced, skipped };
5254
+ }
5255
+ var AutoMemory = class {
5256
+ #deps;
5257
+ #timers = /* @__PURE__ */ new Map();
5258
+ #settings = DEFAULT_AUTO_SETTINGS;
5259
+ #cursors = /* @__PURE__ */ new Map();
5260
+ /** One pass at a time: each one calls a model. */
5261
+ #queue = Promise.resolve();
5262
+ #stop = new AbortController();
5263
+ loaded;
5264
+ constructor(deps) {
5265
+ this.#deps = deps;
5266
+ this.loaded = this.#load();
5267
+ }
5268
+ get settings() {
5269
+ return this.#settings;
5270
+ }
5271
+ /** Kept on by low-context mode, whatever the switch says. */
5272
+ get forced() {
5273
+ return this.#deps.forced?.() === true;
5274
+ }
5275
+ /** Does it read conversations now? */
5276
+ get on() {
5277
+ return this.#settings.auto || this.forced;
5278
+ }
5279
+ async setSettings(settings) {
5280
+ await this.loaded;
5281
+ this.#settings = settings;
5282
+ if (!this.on)
5283
+ this.#clearTimers();
5284
+ await this.#save();
5285
+ return settings;
5286
+ }
5287
+ /** A session started or stopped working: read it once it has been quiet for a while. */
5288
+ activity(sessionId, running) {
5289
+ const timer = this.#timers.get(sessionId);
5290
+ if (timer !== void 0)
5291
+ clearTimeout(timer);
5292
+ this.#timers.delete(sessionId);
5293
+ if (running || !this.on || this.#stop.signal.aborted)
5294
+ return;
5295
+ if (this.#deps.agentOf(sessionId) === void 0)
5296
+ return;
5297
+ const next = setTimeout(() => {
5298
+ this.#timers.delete(sessionId);
5299
+ void this.run(sessionId).then((outcome) => {
5300
+ if (outcome.kind === "done" && outcome.added + outcome.replaced > 0)
5301
+ this.#deps.log.info(`memory from ${sessionId}: ${outcome.added} added, ${outcome.replaced} changed`);
5302
+ }, (error) => this.#deps.log.warn(`memory from ${sessionId}: ${error instanceof Error ? error.message : String(error)}`));
5303
+ }, this.#deps.idleMs ?? DEFAULT_IDLE_MS);
5304
+ next.unref?.();
5305
+ this.#timers.set(sessionId, next);
5306
+ }
5307
+ /** Read what is new in a session and keep what is worth it (queued behind any pass under way). */
5308
+ run(sessionId) {
5309
+ const pass = this.#queue.then(() => this.#pass(sessionId));
5310
+ this.#queue = pass.catch(() => {
4772
5311
  });
5312
+ return pass;
4773
5313
  }
4774
- /**
4775
- * Answer a question. Every question of the request gets exactly one item:
4776
- * unknown ids are dropped, missing ones count as skipped.
4777
- * @returns false when the question is unknown or already settled.
4778
- */
4779
- respond(questionId, answers) {
4780
- const entry = this.pending.get(questionId);
4781
- if (entry === void 0)
4782
- return false;
4783
- const items = entry.request.questions.map((q) => {
4784
- const given = answers.find((a) => a.id === q.id);
4785
- const custom = given?.custom?.trim();
4786
- return { id: q.id, selected: [...given?.selected ?? []], ...custom === void 0 || custom === "" ? {} : { custom } };
5314
+ dispose() {
5315
+ this.#stop.abort();
5316
+ this.#clearTimers();
5317
+ }
5318
+ async #pass(sessionId) {
5319
+ await this.loaded;
5320
+ await this.#deps.store.loaded;
5321
+ if (!this.on)
5322
+ return { kind: "skipped", why: "off" };
5323
+ const agent = this.#deps.agentOf(sessionId);
5324
+ if (agent === void 0)
5325
+ return { kind: "skipped", why: "not an agent of the app" };
5326
+ const signal = AbortSignal.any([this.#stop.signal, AbortSignal.timeout(12e4)]);
5327
+ const events = await this.#deps.read(sessionId, signal);
5328
+ const after = this.#cursors.get(sessionId) ?? -1;
5329
+ const exchanges = exchangesOf(events, after);
5330
+ const last = Math.max(after, ...events.map((e) => e.seq));
5331
+ if (!exchanges.some((e) => e.from === "user") || !exchanges.some((e) => e.from === "agent")) {
5332
+ await this.#moveTo(sessionId, last);
5333
+ return { kind: "skipped", why: "nothing said by the user" };
5334
+ }
5335
+ const selection = this.#settings.model ?? this.#deps.defaultModel();
5336
+ if (selection === void 0)
5337
+ return { kind: "skipped", why: "no model" };
5338
+ const memories = this.#deps.store.visibleTo(agent.id);
5339
+ const answer = await this.#deps.complete({
5340
+ selection,
5341
+ system: extractionSystem(agent.name, day(Date.now(), this.#deps.timeZone)),
5342
+ prompt: extractionPrompt(memories, exchanges, agent.id, this.#deps.timeZone),
5343
+ signal
4787
5344
  });
4788
- return this.settle(questionId, "answered", { answers: items });
5345
+ const applied = await applyOps(this.#deps.store, parseOps(answer), agent.id);
5346
+ await this.#moveTo(sessionId, last);
5347
+ return { kind: "done", ...applied };
4789
5348
  }
4790
- /** Questions still waiting, for replay to a newly connected client. */
4791
- open() {
4792
- return [...this.pending.values()].map((p) => p.request);
5349
+ async #moveTo(sessionId, seq) {
5350
+ if (seq < 0 || this.#cursors.get(sessionId) === seq)
5351
+ return;
5352
+ this.#cursors.delete(sessionId);
5353
+ this.#cursors.set(sessionId, seq);
5354
+ while (this.#cursors.size > MAX_CURSORS)
5355
+ this.#cursors.delete(this.#cursors.keys().next().value);
5356
+ await this.#save();
4793
5357
  }
4794
- /** Fail every pending question (gateway unloading). */
4795
- dispose() {
4796
- for (const id of [...this.pending.keys()])
4797
- this.settle(id, "unavailable");
5358
+ #clearTimers() {
5359
+ for (const timer of this.#timers.values())
5360
+ clearTimeout(timer);
5361
+ this.#timers.clear();
5362
+ }
5363
+ async #load() {
5364
+ if (this.#deps.file === void 0)
5365
+ return;
5366
+ try {
5367
+ const saved = JSON.parse(await readFile5(this.#deps.file, "utf8"));
5368
+ const settings = external_exports.object({ auto: external_exports.boolean(), model: external_exports.object({ provider: external_exports.string(), model: external_exports.string(), reasoningEffort: external_exports.string().optional() }).nullable() }).safeParse(saved.settings);
5369
+ if (settings.success)
5370
+ this.#settings = settings.data;
5371
+ if (typeof saved.cursors === "object" && saved.cursors !== null) {
5372
+ for (const [id, seq] of Object.entries(saved.cursors))
5373
+ if (typeof seq === "number")
5374
+ this.#cursors.set(id, seq);
5375
+ }
5376
+ } catch {
5377
+ }
4798
5378
  }
4799
- settle(questionId, outcome, answer) {
4800
- const entry = this.pending.get(questionId);
4801
- if (entry === void 0)
4802
- return false;
4803
- this.pending.delete(questionId);
4804
- entry.settle(outcome, answer);
4805
- this.options.broadcastResolved(questionId, outcome, answer?.answers);
4806
- for (const answerer of this.answerers)
4807
- safely2(() => answerer.resolved(questionId, outcome, answer?.answers), void 0);
4808
- return true;
5379
+ async #save() {
5380
+ if (this.#deps.file === void 0)
5381
+ return;
5382
+ await writeFileAtomic(this.#deps.file, `${JSON.stringify({ settings: this.#settings, cursors: Object.fromEntries(this.#cursors) })}
5383
+ `);
4809
5384
  }
4810
5385
  };
4811
- function safely2(fn, fallback) {
4812
- try {
4813
- return fn();
4814
- } catch {
4815
- return fallback;
5386
+
5387
+ // packages/gateway/lib/history.js
5388
+ var NOTE_SOURCES = /* @__PURE__ */ new Set(["time-context", "adg-time"]);
5389
+ var SEARCH_DEPTH = 1500;
5390
+ var SEARCH_SESSIONS = 20;
5391
+ var MAX_LINE = 1500;
5392
+ var SNIPPET = 160;
5393
+ function textOf2(content) {
5394
+ return content.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("\n").trim();
5395
+ }
5396
+ function saidIn(events) {
5397
+ const out = [];
5398
+ for (const event of events) {
5399
+ if (event.type === "user/message") {
5400
+ if (NOTE_SOURCES.has(event.origin.kind))
5401
+ continue;
5402
+ const text = textOf2(event.content);
5403
+ if (text !== "")
5404
+ out.push({ seq: event.seq, time: event.time, from: event.origin.human ? "user" : "app", text, ...event.replacesHistory === true ? { summary: true } : {} });
5405
+ } else if (event.type === "assistant/message") {
5406
+ const text = textOf2(event.content);
5407
+ if (text !== "")
5408
+ out.push({ seq: event.seq, time: event.time, from: "agent", text });
5409
+ }
4816
5410
  }
5411
+ return out;
5412
+ }
5413
+ var WHO = { user: "\u7528\u6237", app: "\u8F6F\u4EF6/\u540C\u4E8B", agent: "\u4F60" };
5414
+ function clock(time, timeZone) {
5415
+ const parts = new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(new Date(time));
5416
+ const get = (type) => parts.find((p) => p.type === type)?.value ?? "";
5417
+ return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")}`;
5418
+ }
5419
+ function line(said, timeZone, max = MAX_LINE) {
5420
+ const text = said.text.length > max ? `${said.text.slice(0, max)}\u2026\uFF08\u540E\u9762\u7701\u7565 ${said.text.length - max} \u5B57\uFF09` : said.text;
5421
+ return `#${said.seq} ${clock(said.time, timeZone)} ${said.summary === true ? "\uFF08\u538B\u7F29\u6458\u8981\uFF09" : WHO[said.from]}\uFF1A${text}`;
5422
+ }
5423
+ function matches(text, terms) {
5424
+ const lower = text.toLowerCase();
5425
+ return terms.every((term) => lower.includes(term));
5426
+ }
5427
+ function snippet(text, terms) {
5428
+ const flat = text.replace(/\s+/g, " ");
5429
+ const at = Math.max(0, ...terms.map((t) => flat.toLowerCase().indexOf(t)).filter((i) => i >= 0).slice(0, 1));
5430
+ const start = Math.max(0, at - SNIPPET / 2);
5431
+ const end = Math.min(flat.length, start + SNIPPET);
5432
+ return `${start > 0 ? "\u2026" : ""}${flat.slice(start, end)}${end < flat.length ? "\u2026" : ""}`;
5433
+ }
5434
+ function around(said, seq, before, after) {
5435
+ let at = said.findIndex((s) => s.seq >= seq);
5436
+ if (at === -1)
5437
+ at = said.length - 1;
5438
+ return said.slice(Math.max(0, at - before), at + after + 1);
5439
+ }
5440
+ var SearchArgs2 = external_exports.object({
5441
+ query: external_exports.string().trim().min(1),
5442
+ days: external_exports.number().int().min(1).max(3650).nullish(),
5443
+ session_id: external_exports.string().nullish(),
5444
+ limit: external_exports.number().int().min(1).max(50).nullish()
5445
+ });
5446
+ var ReadArgs = external_exports.object({
5447
+ seq: external_exports.number().int().min(0),
5448
+ session_id: external_exports.string().nullish(),
5449
+ before: external_exports.number().int().min(0).max(30).nullish(),
5450
+ after: external_exports.number().int().min(0).max(30).nullish()
5451
+ });
5452
+ function parse2(schema, args) {
5453
+ const parsed = schema.safeParse(args ?? {});
5454
+ if (!parsed.success)
5455
+ throw new Error(`\u53C2\u6570\u65E0\u6548\uFF1A${parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"} ${i.message}`).join("; ")}`);
5456
+ return parsed.data;
5457
+ }
5458
+ var render2 = (_args, value) => [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 1) }];
5459
+ function historyTools(deps) {
5460
+ const caller2 = (exec) => {
5461
+ const session = exec.agent?.session.id;
5462
+ const agent = session === void 0 ? void 0 : deps.agentOf(session);
5463
+ if (session === void 0 || agent === void 0)
5464
+ throw new Error("\u53EA\u6709\u672C\u8F6F\u4EF6\u7684 agent \u80FD\u67E5\u5BF9\u8BDD\u8BB0\u5F55");
5465
+ return { agent, session };
5466
+ };
5467
+ const reachable = async (agent, current, signal) => {
5468
+ const all = await deps.sessions(agent, signal);
5469
+ const here = all.find((s) => s.id === current) ?? { id: current, title: null };
5470
+ return [here, ...all.filter((s) => s.id !== current)];
5471
+ };
5472
+ const search = {
5473
+ name: "history_search",
5474
+ description: [
5475
+ "\u6309\u5173\u952E\u8BCD\u67E5\u4F60\u4EE5\u524D\u7684\u5BF9\u8BDD\u539F\u6587\uFF08\u8FD9\u4E2A\u5BF9\u8BDD\u91CC\u88AB\u538B\u7F29\u6389\u7684\u90E8\u5206\uFF0C\u548C\u4F60\u66F4\u65E9\u7684\u5BF9\u8BDD\uFF09\u3002",
5476
+ "\u5BF9\u8BDD\u8F83\u65E9\u7684\u90E8\u5206\u53EF\u80FD\u5DF2\u7ECF\u538B\u7F29\u6210\u4E86\u6458\u8981\uFF1A\u8981\u7528\u6237\u7684\u539F\u8BDD\u3001\u5177\u4F53\u7684\u6570\u5B57\u548C\u540D\u5B57\u3001\u5F53\u65F6\u7684\u8F93\u51FA\u65F6\u7528\u5B83\u3002",
5477
+ "query \u5199\u51E0\u4E2A\u5173\u952E\u8BCD\uFF08\u7A7A\u683C\u5206\u5F00\uFF0C\u5168\u90E8\u5305\u542B\u624D\u7B97\uFF09\uFF1B\u627E\u5230\u7684\u6BCF\u6761\u5E26 #\u7F16\u53F7\uFF0C\u7528 history_read \u8BFB\u90A3\u4E00\u6BB5\u7684\u524D\u540E\u6587\u3002",
5478
+ "\u5148\u67E5\u8BB0\u5FC6\uFF08memory_search\uFF09\uFF1B\u8BB0\u5FC6\u91CC\u6CA1\u6709\u3001\u6216\u8981\u539F\u8BDD\u65F6\u518D\u67E5\u8FD9\u91CC\u3002"
5479
+ ].join(""),
5480
+ parameters: {
5481
+ type: "object",
5482
+ properties: {
5483
+ query: { type: "string", description: "\u5173\u952E\u8BCD\uFF0C\u7A7A\u683C\u5206\u5F00\u3002" },
5484
+ days: { type: "number", description: "\u53EA\u67E5\u6700\u8FD1\u51E0\u5929\uFF08\u53EF\u9009\uFF09\u3002" },
5485
+ session_id: { type: "string", description: "\u53EA\u67E5\u8FD9\u4E2A\u5BF9\u8BDD\uFF08\u53EF\u9009\uFF1B\u9ED8\u8BA4\u4F60\u6240\u6709\u7684\u5BF9\u8BDD\uFF0C\u8FD9\u4E2A\u5BF9\u8BDD\u5728\u524D\uFF09\u3002" },
5486
+ limit: { type: "number", description: "\u6700\u591A\u51E0\u6761\uFF08\u9ED8\u8BA4 20\uFF09\u3002" }
5487
+ },
5488
+ required: ["query"],
5489
+ additionalProperties: false
5490
+ },
5491
+ output: { schema: {}, render: render2 },
5492
+ timeoutMs: 6e4,
5493
+ isConcurrencySafe: () => true,
5494
+ execute: async (args, exec) => {
5495
+ const { agent, session } = caller2(exec);
5496
+ const { query, days, session_id, limit } = parse2(SearchArgs2, args);
5497
+ const signal = exec.signal ?? new AbortController().signal;
5498
+ const terms = query.toLowerCase().split(/\s+/).filter((t) => t !== "");
5499
+ const since = days == null ? 0 : Date.now() - days * 24 * 60 * 6e4;
5500
+ const sessions = (await reachable(agent, session, signal)).filter((s) => session_id == null || s.id === session_id);
5501
+ if (session_id != null && sessions.length === 0)
5502
+ throw new Error(`\u6CA1\u6709\u8FD9\u4E2A\u5BF9\u8BDD\uFF1A${session_id}\uFF08\u53EA\u80FD\u67E5\u4F60\u81EA\u5DF1\u7684\u5BF9\u8BDD\uFF09`);
5503
+ const max = limit ?? 20;
5504
+ const items = [];
5505
+ for (const s of sessions.slice(0, SEARCH_SESSIONS)) {
5506
+ if (items.length >= max || signal.aborted)
5507
+ break;
5508
+ const said = saidIn(await deps.read(s.id, SEARCH_DEPTH, signal));
5509
+ for (let i = said.length - 1; i >= 0 && items.length < max; i--) {
5510
+ const m = said[i];
5511
+ if (m.time < since)
5512
+ break;
5513
+ if (!matches(m.text, terms))
5514
+ continue;
5515
+ items.push({ session_id: s.id, title: s.id === session ? "\uFF08\u8FD9\u4E2A\u5BF9\u8BDD\uFF09" : s.title, seq: m.seq, time: clock(m.time, deps.timeZone), from: m.summary === true ? "\u538B\u7F29\u6458\u8981" : WHO[m.from], text: snippet(m.text, terms) });
5516
+ }
5517
+ }
5518
+ return items.length === 0 ? { items, note: "\u6CA1\u6709\u627E\u5230\u3002\u6362\u4E2A\u8BF4\u6CD5\u6216\u66F4\u5C11\u7684\u5173\u952E\u8BCD\u518D\u67E5\uFF1B\u4E5F\u53EF\u80FD\u5C31\u662F\u6CA1\u8BF4\u8FC7\u3002" } : { items, note: "\u7528 history_read \u7684 seq\uFF08\u548C session_id\uFF09\u8BFB\u524D\u540E\u6587\u3002" };
5519
+ },
5520
+ presentCall: (args) => ({ card: "generic", title: `\u67E5\u5BF9\u8BDD\u8BB0\u5F55\uFF1A${String(args?.query ?? "")}`, kind: "other" })
5521
+ };
5522
+ const read = {
5523
+ name: "history_read",
5524
+ description: "\u8BFB\u4F60\u4EE5\u524D\u5BF9\u8BDD\u91CC\u7684\u4E00\u6BB5\u539F\u6587\uFF1A#\u7F16\u53F7\uFF08seq\uFF0C\u6765\u81EA history_search \u6216\u538B\u7F29\u6458\u8981\uFF09\u90A3\u6761\u6D88\u606F\uFF0C\u548C\u5B83\u524D\u540E\u51E0\u6761\u3002session_id \u4E0D\u5199\u5C31\u662F\u8FD9\u4E2A\u5BF9\u8BDD\u3002",
5525
+ parameters: {
5526
+ type: "object",
5527
+ properties: {
5528
+ seq: { type: "number", description: "\u6D88\u606F\u7684\u7F16\u53F7\uFF08#\u540E\u9762\u7684\u6570\u5B57\uFF09\u3002" },
5529
+ session_id: { type: "string", description: "\u54EA\u4E2A\u5BF9\u8BDD\uFF08\u53EF\u9009\uFF0C\u9ED8\u8BA4\u8FD9\u4E2A\u5BF9\u8BDD\uFF09\u3002" },
5530
+ before: { type: "number", description: "\u5F80\u524D\u8BFB\u51E0\u6761\uFF08\u9ED8\u8BA4 4\uFF09\u3002" },
5531
+ after: { type: "number", description: "\u5F80\u540E\u8BFB\u51E0\u6761\uFF08\u9ED8\u8BA4 4\uFF09\u3002" }
5532
+ },
5533
+ required: ["seq"],
5534
+ additionalProperties: false
5535
+ },
5536
+ output: { schema: {}, render: render2 },
5537
+ timeoutMs: 6e4,
5538
+ isConcurrencySafe: () => true,
5539
+ execute: async (args, exec) => {
5540
+ const { agent, session } = caller2(exec);
5541
+ const { seq, session_id, before, after } = parse2(ReadArgs, args);
5542
+ const signal = exec.signal ?? new AbortController().signal;
5543
+ const target = session_id ?? session;
5544
+ if (target !== session && !(await deps.sessions(agent, signal)).some((s) => s.id === target))
5545
+ throw new Error(`\u6CA1\u6709\u8FD9\u4E2A\u5BF9\u8BDD\uFF1A${target}\uFF08\u53EA\u80FD\u8BFB\u4F60\u81EA\u5DF1\u7684\u5BF9\u8BDD\uFF09`);
5546
+ let said = [];
5547
+ for (const depth of [400, SEARCH_DEPTH, 1e4]) {
5548
+ said = saidIn(await deps.read(target, depth, signal));
5549
+ if (said.length === 0 || said[0].seq <= seq)
5550
+ break;
5551
+ }
5552
+ if (said.length === 0)
5553
+ return "\u8FD9\u4E2A\u5BF9\u8BDD\u91CC\u8FD8\u6CA1\u6709\u6D88\u606F\u3002";
5554
+ const picked = around(said, seq, before ?? 4, after ?? 4);
5555
+ return [`\u5BF9\u8BDD ${target === session ? "\uFF08\u8FD9\u4E2A\u5BF9\u8BDD\uFF09" : target}\uFF0C#${picked[0].seq}\u2013#${picked.at(-1).seq}\uFF1A`, ...picked.map((s) => line(s, deps.timeZone))].join("\n\n");
5556
+ },
5557
+ presentCall: (args) => ({ card: "generic", title: `\u8BFB\u5BF9\u8BDD\u8BB0\u5F55 #${String(args?.seq ?? "")}`, kind: "other" })
5558
+ };
5559
+ return [search, read];
4817
5560
  }
4818
5561
 
4819
5562
  // packages/gateway/lib/convert.js
@@ -5221,6 +5964,123 @@ function convertLiveBaseline(baseline) {
5221
5964
  };
5222
5965
  }
5223
5966
 
5967
+ // packages/gateway/lib/questions.js
5968
+ var QuestionClosed = class extends Error {
5969
+ outcome;
5970
+ constructor(outcome) {
5971
+ super(outcome === "cancelled" ? "the question was withdrawn" : "the question can no longer be answered");
5972
+ this.outcome = outcome;
5973
+ }
5974
+ };
5975
+ var QuestionBroker = class {
5976
+ pending = /* @__PURE__ */ new Map();
5977
+ answerers = /* @__PURE__ */ new Set();
5978
+ options;
5979
+ constructor(options) {
5980
+ this.options = options;
5981
+ }
5982
+ /** @returns a disposer. */
5983
+ addAnswerer(answerer) {
5984
+ this.answerers.add(answerer);
5985
+ return () => {
5986
+ this.answerers.delete(answerer);
5987
+ };
5988
+ }
5989
+ /** Whether some answerer besides protocol clients can take a question from `sessionId` now. */
5990
+ hasActiveAnswerer(sessionId) {
5991
+ for (const answerer of this.answerers)
5992
+ if (safely2(() => answerer.active(sessionId), false))
5993
+ return true;
5994
+ return false;
5995
+ }
5996
+ /**
5997
+ * Put the questions to the clients and answerers and wait for the first answer.
5998
+ * @throws QuestionClosed when the agent stops waiting or the broker goes away.
5999
+ */
6000
+ ask(ask) {
6001
+ if (ask.signal?.aborted === true)
6002
+ return Promise.reject(new QuestionClosed("cancelled"));
6003
+ const questionId = crypto.randomUUID();
6004
+ const request = {
6005
+ questionId,
6006
+ sessionId: ask.sessionId,
6007
+ ...ask.callId === void 0 ? {} : { callId: ask.callId },
6008
+ questions: ask.questions.map((q) => ({
6009
+ id: q.id,
6010
+ question: q.question,
6011
+ ...q.detail === void 0 ? {} : { detail: q.detail },
6012
+ ...q.header === void 0 ? {} : { header: q.header },
6013
+ ...q.options === void 0 ? {} : { options: q.options.map((o) => ({ label: o.label, ...o.description === void 0 ? {} : { description: o.description } })) },
6014
+ ...q.multiSelect === void 0 ? {} : { multiSelect: q.multiSelect }
6015
+ }))
6016
+ };
6017
+ return new Promise((resolve3, reject) => {
6018
+ const onAbort = () => this.settle(questionId, "cancelled");
6019
+ this.pending.set(questionId, {
6020
+ request,
6021
+ settle: (outcome, answer) => {
6022
+ ask.signal?.removeEventListener("abort", onAbort);
6023
+ if (outcome === "answered" && answer !== void 0)
6024
+ resolve3(answer);
6025
+ else
6026
+ reject(new QuestionClosed(outcome === "answered" ? "unavailable" : outcome));
6027
+ }
6028
+ });
6029
+ ask.signal?.addEventListener("abort", onAbort, { once: true });
6030
+ this.options.broadcastRequested(request);
6031
+ for (const answerer of this.answerers) {
6032
+ if (!this.pending.has(questionId))
6033
+ break;
6034
+ if (safely2(() => answerer.active(request.sessionId), false))
6035
+ safely2(() => answerer.asked(request), void 0);
6036
+ }
6037
+ });
6038
+ }
6039
+ /**
6040
+ * Answer a question. Every question of the request gets exactly one item:
6041
+ * unknown ids are dropped, missing ones count as skipped.
6042
+ * @returns false when the question is unknown or already settled.
6043
+ */
6044
+ respond(questionId, answers) {
6045
+ const entry = this.pending.get(questionId);
6046
+ if (entry === void 0)
6047
+ return false;
6048
+ const items = entry.request.questions.map((q) => {
6049
+ const given = answers.find((a) => a.id === q.id);
6050
+ const custom = given?.custom?.trim();
6051
+ return { id: q.id, selected: [...given?.selected ?? []], ...custom === void 0 || custom === "" ? {} : { custom } };
6052
+ });
6053
+ return this.settle(questionId, "answered", { answers: items });
6054
+ }
6055
+ /** Questions still waiting, for replay to a newly connected client. */
6056
+ open() {
6057
+ return [...this.pending.values()].map((p) => p.request);
6058
+ }
6059
+ /** Fail every pending question (gateway unloading). */
6060
+ dispose() {
6061
+ for (const id of [...this.pending.keys()])
6062
+ this.settle(id, "unavailable");
6063
+ }
6064
+ settle(questionId, outcome, answer) {
6065
+ const entry = this.pending.get(questionId);
6066
+ if (entry === void 0)
6067
+ return false;
6068
+ this.pending.delete(questionId);
6069
+ entry.settle(outcome, answer);
6070
+ this.options.broadcastResolved(questionId, outcome, answer?.answers);
6071
+ for (const answerer of this.answerers)
6072
+ safely2(() => answerer.resolved(questionId, outcome, answer?.answers), void 0);
6073
+ return true;
6074
+ }
6075
+ };
6076
+ function safely2(fn, fallback) {
6077
+ try {
6078
+ return fn();
6079
+ } catch {
6080
+ return fallback;
6081
+ }
6082
+ }
6083
+
5224
6084
  // packages/gateway/lib/builtin.js
5225
6085
  function handlers(map) {
5226
6086
  return map;
@@ -5544,7 +6404,7 @@ function builtinCapabilities(deps) {
5544
6404
  }
5545
6405
 
5546
6406
  // packages/gateway/lib/homes.js
5547
- import { readFile as readFile4 } from "node:fs/promises";
6407
+ import { readFile as readFile6 } from "node:fs/promises";
5548
6408
  import { mkdirSync } from "node:fs";
5549
6409
  import { dirname } from "node:path";
5550
6410
  var AgentHomes = class {
@@ -5586,7 +6446,7 @@ var AgentHomes = class {
5586
6446
  if (this.#file === void 0)
5587
6447
  return;
5588
6448
  try {
5589
- const saved = JSON.parse(await readFile4(this.#file, "utf8"));
6449
+ const saved = JSON.parse(await readFile6(this.#file, "utf8"));
5590
6450
  if (saved === null || typeof saved !== "object")
5591
6451
  return;
5592
6452
  for (const [agent, session] of Object.entries(saved))
@@ -5653,7 +6513,7 @@ var HandOffs = class {
5653
6513
  if (this.#file === void 0)
5654
6514
  return;
5655
6515
  try {
5656
- const saved = JSON.parse(await readFile4(this.#file, "utf8"));
6516
+ const saved = JSON.parse(await readFile6(this.#file, "utf8"));
5657
6517
  if (!Array.isArray(saved))
5658
6518
  return;
5659
6519
  for (const item of saved) {
@@ -5706,7 +6566,7 @@ function duration(seconds) {
5706
6566
  }
5707
6567
 
5708
6568
  // packages/gateway/lib/last-reply.js
5709
- var MAX_CHARS = 280;
6569
+ var MAX_CHARS2 = 280;
5710
6570
  var READ_BACK = 6;
5711
6571
  var KEPT = 500;
5712
6572
  var LastReplies = class {
@@ -5765,22 +6625,24 @@ function lastReply(events) {
5765
6625
  }
5766
6626
  function plain(markdown) {
5767
6627
  const words = markdown.replace(/```[\s\S]*?```/g, " ").replace(/!\[[^\]]*\]\([^)]*\)/g, " ").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+\.)\s+/gm, "").replace(/^\s*\|?\s*:?-{3,}.*$/gm, " ").replace(/[*_`~|]/g, "").replace(/\s+/g, " ").trim();
5768
- return words.length > MAX_CHARS ? `${words.slice(0, MAX_CHARS)}\u2026` : words;
6628
+ return words.length > MAX_CHARS2 ? `${words.slice(0, MAX_CHARS2)}\u2026` : words;
5769
6629
  }
5770
6630
 
5771
6631
  // packages/gateway/lib/roles.js
5772
- import { readFile as readFile5 } from "node:fs/promises";
6632
+ import { readFile as readFile7 } from "node:fs/promises";
5773
6633
  import { mkdirSync as mkdirSync2 } from "node:fs";
5774
6634
  import { dirname as dirname2 } from "node:path";
5775
6635
  function keeps(tools, name) {
5776
- return tools === void 0 || matches(tools, name);
6636
+ return tools === void 0 || matches2(tools, name);
5777
6637
  }
5778
- function matches(patterns, name) {
6638
+ function matches2(patterns, name) {
5779
6639
  return patterns.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
5780
6640
  }
5781
6641
  var NOBODY = ["subagent_fork"];
5782
6642
  var TOGETHER = ["agent_delegate", "agent_message", "agent_threads"];
5783
- var COORDINATION = ["agent_delegate", "agent_message", "agent_threads", "notice_act", "ask_user_question", "exit_plan_mode", "subagent", "list_agents", "interrupt_agent", "schedule_*", "create_goal", "update_goal", "get_goal", "intervention_done"];
6643
+ var MEMORY_TOOLS = ["memory_save", "memory_forget", "memory_search", "history_search", "history_read"];
6644
+ var ALWAYS = [...TOGETHER, ...MEMORY_TOOLS];
6645
+ var COORDINATION = ["agent_delegate", "agent_message", "agent_threads", "notice_act", "ask_user_question", "exit_plan_mode", "subagent", "list_agents", "interrupt_agent", "schedule_*", "create_goal", "update_goal", "get_goal", "intervention_done", "memory_save", "memory_forget"];
5784
6646
  var HANDS_ON = [
5785
6647
  ...AGENT_AREAS.filter((area) => ["run", "scripts-config", "scripts-install", "screen", "games", "shell"].includes(area.id)).flatMap((area) => area.tools).filter((tool) => tool !== "pipeline_run"),
5786
6648
  // Screenshots are not in an area (they change nothing), and they weigh the most.
@@ -5790,11 +6652,11 @@ var HANDS_ON = [
5790
6652
  ];
5791
6653
  var HANDS_ON_REFUSAL = (tool) => `${tool} \u8FD9\u7C7B\u5177\u4F53\u64CD\u4F5C\u4E0D\u5728\u4F60\u7684\u5BF9\u8BDD\u91CC\u505A\uFF1A\u7528 subagent \u5F00\u4E00\u4E2A\u5B50 agent \u53BB\u505A\uFF0C\u628A\u4EFB\u52A1\u5199\u5B8C\u6574\uFF08\u5B83\u770B\u4E0D\u5230\u4F60\u7684\u5BF9\u8BDD\uFF09\uFF0C\u5B83\u53EA\u628A\u7ED3\u679C\u4EA4\u56DE\u6765\u3002\u8981\u7528\u6237\u6279\u51C6\u7684\u64CD\u4F5C\uFF0C\u5B83\u505A\u7684\u65F6\u5019\u540C\u6837\u4F1A\u8BF7\u7528\u6237\u6279\u51C6\u3002`;
5792
6654
  function handsOn(tool) {
5793
- return matches(HANDS_ON, tool);
6655
+ return matches2(HANDS_ON, tool);
5794
6656
  }
5795
6657
  function hiddenTools(spec, appTools, visible, home = false) {
5796
6658
  const hide = [...NOBODY, ...spec.hide ?? [], ...home ? HANDS_ON : []];
5797
- return [...visible].filter((name) => matches(hide, name) || appTools.has(name) && !keeps(spec.tools, name) && !TOGETHER.includes(name));
6659
+ return [...visible].filter((name) => matches2(hide, name) || appTools.has(name) && !keeps(spec.tools, name) && !ALWAYS.includes(name));
5798
6660
  }
5799
6661
  function subAgentSpec(parent) {
5800
6662
  const name = parent.name;
@@ -5818,14 +6680,14 @@ function subAgentSpec(parent) {
5818
6680
  }
5819
6681
  function teamPrompt(self, main, leads) {
5820
6682
  const who = (m) => `\u300C${m.name}\u300D\uFF08${m.id}${m.alias === void 0 ? "" : `\uFF0C\u7528\u6237\u4E5F\u53EB\u5B83\u300C${m.alias}\u300D`}\uFF09`;
5821
- const line = (m) => `- ${who(m)}${m.description === "" ? "" : `\uFF1A${m.description}`}`;
6683
+ const line2 = (m) => `- ${who(m)}${m.description === "" ? "" : `\uFF1A${m.description}`}`;
5822
6684
  const colleagues = leads.filter((m) => m.id !== self.id);
5823
6685
  const isMain = self.id === main.id;
5824
6686
  return [
5825
6687
  "# \u56E2\u961F",
5826
6688
  isMain ? `\u4F60\u662F\u300C${self.name}\u300D\uFF08${self.id}\uFF09\uFF0C\u662F\u6700\u4E0A\u7EA7\u7684 agent\uFF1A\u548C\u7528\u6237\u5BF9\u8BDD\uFF0C\u628A\u4E8B\u5206\u7ED9\u4E0B\u9762\u7684\u4E3B agent\uFF0C\u6C47\u603B\u7ED3\u679C\u5E76\u505A\u51B3\u5B9A\u3002` : `\u4F60\u662F\u300C${self.name}\u300D\uFF08${self.id}\uFF09\uFF0C\u662F\u4E00\u4E2A\u4E3B agent\uFF1A\u8D1F\u8D23\u81EA\u5DF1\u8FD9\u5757\u4E8B\uFF0C\u505A\u51B3\u5B9A\u3001\u6C47\u603B\u7ED3\u679C\u3002\u4E0A\u7EA7\u662F${who(main)}\uFF1A\u5B83\u548C\u7528\u6237\u5BF9\u8BDD\u3001\u5206\u53D1\u4EFB\u52A1\u3001\u505A\u51B3\u5B9A\u3002`,
5827
6689
  colleagues.length === 0 ? isMain ? "\u73B0\u5728\u6CA1\u6709\u5176\u4ED6\u4E3B agent\u3002" : "\u73B0\u5728\u6CA1\u6709\u5176\u4ED6\u540C\u4E8B\u3002" : `${isMain ? "\u4E0B\u9762\u7684\u4E3B agent" : "\u540C\u4E8B"}\uFF1A
5828
- ${colleagues.map(line).join("\n")}`,
6690
+ ${colleagues.map(line2).join("\n")}`,
5829
6691
  "\u5177\u4F53\u7684\u6D3B\u90FD\u7531\u5B50 agent \u505A\uFF08subagent\uFF09\uFF1A\u8FD0\u884C\u547D\u4EE4\u3001\u6539\u6587\u4EF6\u3001\u622A\u56FE\u70B9\u51FB\u3001\u8FD0\u884C\u548C\u5B89\u88C5\u811A\u672C\u3001\u542F\u52A8\u6E38\u620F\uFF0C\u8FD9\u4E9B\u5DE5\u5177\u4E0D\u5728\u4F60\u7684\u5BF9\u8BDD\u91CC\uFF0C\u53EA\u6709\u5B50 agent \u6709\uFF1B\u522B\u5904\u63D0\u5230\u8FD9\u4E9B\u5DE5\u5177\uFF0C\u4E5F\u662F\u8BA9\u5B50 agent \u53BB\u7528\u3002\u4F60\u7684\u5BF9\u8BDD\u7559\u7ED9\u5224\u65AD\u548C\u6C47\u603B\uFF1A\u8981\u505A\u4EC0\u4E48\u5C31\u5F00\u4E00\u4E2A\u5B50 agent\uFF0C\u628A\u4EFB\u52A1\u5199\u5B8C\u6574\uFF08\u5B83\u770B\u4E0D\u5230\u4F60\u7684\u5BF9\u8BDD\uFF09\uFF0C\u7ED3\u679C\u4EA4\u56DE\u540E\u7531\u4F60\u5224\u65AD\u3001\u6C47\u603B\u3002\u67E5\u72B6\u6001\u3001\u8BFB\u4E00\u4E0B\u6587\u4EF6\u8FD9\u79CD\u770B\u4E00\u773C\u7684\u4E8B\u53EF\u4EE5\u81EA\u5DF1\u6765\u3002\u51E0\u4EF6\u4E92\u4E0D\u76F8\u5173\u7684\u4E8B\u53EF\u4EE5\u540C\u65F6\u5F00\u3002\u5B50 agent \u53EA\u5BF9\u4F60\u8D1F\u8D23\uFF0C\u53EA\u628A\u7ED3\u679C\u4EA4\u56DE\u7ED9\u4F60\uFF1B\u5B83\u8981\u7528\u6237\u6279\u51C6\u7684\u64CD\u4F5C\uFF0C\u4F1A\u5728\u4F60\u7684\u5BF9\u8BDD\u91CC\u8BF7\u7528\u6237\u6279\u51C6\u3002",
5830
6692
  isMain ? "" : `\u9700\u8981\u540C\u4E8B\u7684\u90A3\u90E8\u5206\uFF0C\u7528 agent_delegate \u76F4\u63A5\u4EA4\u7ED9\u5B83\uFF0C\u4E0D\u7528\u7ED5\u8FC7\u300C${main.name}\u300D\u3002\u4EA4\u7ED9\u4F60\u7684\u4E8B\u6CA1\u8BF4\u6E05\u695A\u65F6\uFF0C\u7528 agent_message \u95EE\u4EA4\u7ED9\u4F60\u7684\u4E00\u65B9\uFF0C\u4E0D\u8981\u81EA\u5DF1\u53BB\u95EE\u7528\u6237\uFF08\u8981\u4E0D\u8981\u95EE\u7528\u6237\u7531\u5BF9\u65B9\u51B3\u5B9A\uFF09\uFF0C\u95EE\u6E05\u695A\u518D\u505A\uFF1B\u505A\u5B8C\u7528 agent_message \u7684 done \u4EA4\u56DE\u7ED3\u8BBA\uFF0C\u6216\u8005\u628A\u7ED3\u8BBA\u5199\u5728\u8FD9\u4E00\u8F6E\u6700\u540E\u4E00\u6BB5\u56DE\u590D\u91CC\u3002`,
5831
6693
  "\u548C\u5176\u4ED6 agent \u8BF4\u8BDD\u4E0D\u662F\u4E00\u95EE\u4E00\u7B54\uFF1A\u505A\u7684\u8FC7\u7A0B\u4E2D\u8981\u8BA9\u5BF9\u65B9\u77E5\u9053\u7684\uFF0C\u7528 agent_message \u7684 update\uFF0C\u9A6C\u4E0A\u9001\u5230\u5B83\u7684\u5BF9\u8BDD\u91CC\uFF0C\u8BF4\u51E0\u6B21\u90FD\u884C\uFF1B\u4E00\u4EF6\u4E8B\u4EA4\u56DE\u7ED3\u8BBA\u4EE5\u540E\u8FD8\u6709\u8BDD\uFF08\u6BD4\u5982\u5B9A\u65F6\u63D0\u9192\u5230\u4E86\uFF09\uFF0C\u540C\u6837\u7528 agent_message \u53D1\u5230\u90A3\u6761\u7EBF\u7D22\uFF0C\u4F60\u7684\u666E\u901A\u56DE\u590D\u5BF9\u65B9\u770B\u4E0D\u5230\u3002",
@@ -5922,7 +6784,7 @@ var SessionRoles = class {
5922
6784
  if (this.#file === void 0)
5923
6785
  return;
5924
6786
  try {
5925
- const saved = JSON.parse(await readFile5(this.#file, "utf8"));
6787
+ const saved = JSON.parse(await readFile7(this.#file, "utf8"));
5926
6788
  if (saved !== null && typeof saved === "object" && !Array.isArray(saved)) {
5927
6789
  for (const [id, tag] of Object.entries(saved)) {
5928
6790
  if (typeof tag === "string")
@@ -5961,7 +6823,7 @@ var RoleModel = class {
5961
6823
  if (this.#file === void 0)
5962
6824
  return;
5963
6825
  try {
5964
- const saved = JSON.parse(await readFile5(this.#file, "utf8"));
6826
+ const saved = JSON.parse(await readFile7(this.#file, "utf8"));
5965
6827
  if (typeof saved?.provider === "string" && typeof saved.model === "string") {
5966
6828
  this.#selection = { provider: saved.provider, model: saved.model, ...typeof saved.reasoningEffort === "string" ? { reasoningEffort: saved.reasoningEffort } : {} };
5967
6829
  }
@@ -6124,7 +6986,7 @@ function toRpcError(error) {
6124
6986
  }
6125
6987
 
6126
6988
  // packages/gateway/lib/permissions.js
6127
- import { readFile as readFile6 } from "node:fs/promises";
6989
+ import { readFile as readFile8 } from "node:fs/promises";
6128
6990
  import { mkdirSync as mkdirSync3 } from "node:fs";
6129
6991
  import { dirname as dirname3 } from "node:path";
6130
6992
  var PRESET = { ask: "workspace-write", full: "full-access" };
@@ -6145,7 +7007,7 @@ var Permissions = class {
6145
7007
  if (this.#file === void 0)
6146
7008
  return;
6147
7009
  try {
6148
- const saved = JSON.parse(await readFile6(this.#file, "utf8"));
7010
+ const saved = JSON.parse(await readFile8(this.#file, "utf8"));
6149
7011
  if (saved.mode === "full")
6150
7012
  this.#mode = "full";
6151
7013
  if (typeof saved.since === "number")
@@ -6410,7 +7272,7 @@ Content-Length: 0\r
6410
7272
  }
6411
7273
 
6412
7274
  // packages/gateway/lib/instances.js
6413
- import { mkdir as mkdir4, readdir, readFile as readFile7, rm as rm2 } from "node:fs/promises";
7275
+ import { mkdir as mkdir4, readdir, readFile as readFile9, rm as rm2 } from "node:fs/promises";
6414
7276
  import { tmpdir } from "node:os";
6415
7277
  import { join as join6, resolve as resolve2 } from "node:path";
6416
7278
  var INSTANCES_DIR = join6(tmpdir(), "MultiGameAssistant", "instances");
@@ -6532,7 +7394,7 @@ var Instances = class {
6532
7394
  continue;
6533
7395
  let other;
6534
7396
  try {
6535
- other = JSON.parse(await readFile7(join6(this.#dir, name), "utf8"));
7397
+ other = JSON.parse(await readFile9(join6(this.#dir, name), "utf8"));
6536
7398
  } catch {
6537
7399
  continue;
6538
7400
  }
@@ -6564,7 +7426,7 @@ var Instances = class {
6564
7426
  };
6565
7427
 
6566
7428
  // packages/gateway/lib/shared.js
6567
- import { readFile as readFile8 } from "node:fs/promises";
7429
+ import { readFile as readFile10 } from "node:fs/promises";
6568
7430
  import { mkdirSync as mkdirSync4 } from "node:fs";
6569
7431
  import { dirname as dirname4 } from "node:path";
6570
7432
  var AGENT_PRESET = "mga";
@@ -6597,7 +7459,7 @@ var OwnSessions = class {
6597
7459
  if (this.#file === void 0)
6598
7460
  return;
6599
7461
  try {
6600
- const saved = JSON.parse(await readFile8(this.#file, "utf8"));
7462
+ const saved = JSON.parse(await readFile10(this.#file, "utf8"));
6601
7463
  if (Array.isArray(saved)) {
6602
7464
  for (const id of saved)
6603
7465
  if (typeof id === "string")
@@ -6679,12 +7541,12 @@ function openInBrowser(url, log) {
6679
7541
  });
6680
7542
  }
6681
7543
  function keptToken(dataDir, log) {
6682
- const fresh = () => randomBytes(18).toString("base64url");
7544
+ const fresh = () => randomBytes2(18).toString("base64url");
6683
7545
  if (dataDir === void 0)
6684
7546
  return fresh();
6685
7547
  const file = join7(dataDir, "gateway-token");
6686
7548
  try {
6687
- const saved = readFileSync2(file, "utf8").trim();
7549
+ const saved = readFileSync3(file, "utf8").trim();
6688
7550
  if (/^[\w-]{16,}$/.test(saved))
6689
7551
  return saved;
6690
7552
  } catch {
@@ -6738,11 +7600,15 @@ var MAIN_AGENT = {
6738
7600
  "window_list"
6739
7601
  ]
6740
7602
  };
7603
+ function memoryOwnerOf(spec) {
7604
+ return spec.subAgentOf === void 0 ? spec.id : spec.id.replace(/:sub$/, "");
7605
+ }
6741
7606
  var MAIN_AGENT_MEMBER = { id: MAIN_AGENT.id, name: MAIN_AGENT.name, description: "\u548C\u7528\u6237\u5BF9\u8BDD\uFF0C\u5206\u53D1\u4EFB\u52A1\uFF0C\u505A\u51B3\u5B9A" };
6742
7607
  function mainDuty(roles) {
6743
7608
  return [
6744
7609
  "# \u4F60\u7684\u89D2\u8272\uFF1A\u52A9\u624B",
6745
7610
  "\u4F60\u662F\u7528\u6237\u7684\u52A9\u624B\uFF1A\u548C\u7528\u6237\u5BF9\u8BDD\uFF0C\u5F04\u6E05\u8981\u505A\u4EC0\u4E48\uFF0C\u5B89\u6392\u8C01\u6765\u505A\u3002\u622A\u56FE\u70B9\u51FB\u3001\u8FD0\u884C\u548C\u5B89\u88C5\u811A\u672C\u3001\u8BFB\u6E38\u620F\u8FD9\u4E9B\u5177\u4F53\u7684\u4E8B\u4EA4\u7ED9\u5BF9\u5E94\u7684 agent\uFF08agent_delegate\uFF09\uFF0C\u4F60\u81EA\u5DF1\u4E0D\u505A\u3002",
7611
+ "\u7528\u6237\u8981\u5728\u6E38\u620F\u91CC\u505A\u4E00\u4EF6\u4E8B\u65F6\uFF0C\u4EA4\u51FA\u53BB\u4E4B\u524D\u5148\u7528 script_list\u3001script_tasks \u770B\u8FD9\u4E2A\u6E38\u620F\u4E0B\u7684\u811A\u672C\u6709\u6CA1\u6709\u8FD9\u4E2A\u529F\u80FD\uFF1A\u6709\uFF0C\u5C31\u4EA4\u7ED9\u300C\u811A\u672C\u300Dagent\uFF0C\u5199\u660E\u7528\u54EA\u4E2A\u811A\u672C\u7684\u54EA\u4E2A\u4EFB\u52A1\u53BB\u505A\uFF1B\u786E\u8BA4\u811A\u672C\u90FD\u505A\u4E0D\u4E86\uFF0C\u624D\u4EA4\u7ED9\u80FD\u622A\u56FE\u70B9\u51FB\u7684 agent \u81EA\u5DF1\u52A8\u624B\uFF0C\u5E76\u5728\u4EFB\u52A1\u91CC\u5199\u4E0A\u811A\u672C\u4E3A\u4EC0\u4E48\u505A\u4E0D\u4E86\u3002",
6746
7612
  roles.length === 0 ? "\u73B0\u5728\u6CA1\u6709\u53EF\u4EE5\u4EA4\u7ED9\u7684 agent\uFF0C\u80FD\u505A\u7684\u4F60\u81EA\u5DF1\u505A\u3002" : `\u53EF\u4EE5\u4EA4\u7ED9\u7684 agent\uFF1A
6747
7613
  ${roles.map((r) => `- ${r.name}\uFF1A${r.description}`).join("\n")}`,
6748
7614
  "\u8FD0\u884C\u547D\u4EE4\u3001\u6539\u6587\u4EF6\u8FD9\u4E9B\u5DE5\u5177\u4E0D\u5728\u4F60\u7684\u5BF9\u8BDD\u91CC\uFF1A\u7528\u6237\u8981\u7684\u8FD9\u7C7B\u4E8B\uFF08\u6574\u7406\u6587\u4EF6\u3001\u5BFC\u51FA\u8BB0\u5F55\u3001\u67E5\u7CFB\u7EDF\uFF09\uFF0C\u8FD8\u6709\u67E5\u8D44\u6599\u3001\u8BFB\u65E5\u5FD7\u3001\u6BD4\u8F83\u51E0\u4E2A\u65B9\u6848\uFF0C\u90FD\u5F00\u81EA\u5DF1\u7684\u5B50 agent\uFF08subagent\uFF09\u53BB\u505A\uFF0C\u5B83\u628A\u7ED3\u679C\u4EA4\u56DE\u6765\uFF0C\u4F60\u544A\u8BC9\u7528\u6237\u3002\u622A\u56FE\u70B9\u51FB\u3001\u8FD0\u884C\u548C\u5B89\u88C5\u811A\u672C\u8FD9\u4E9B\u4EA4\u7ED9\u5BF9\u5E94\u7684\u4E3B agent\u3002",
@@ -6801,6 +7667,9 @@ var AdgGateway = class extends Service {
6801
7667
  narrowed = /* @__PURE__ */ new Map();
6802
7668
  subAgentSpecs = /* @__PURE__ */ new WeakMap();
6803
7669
  persona;
7670
+ /** Long-term memory (memory.ts): every agent's prompt carries what it may read. */
7671
+ memory;
7672
+ compaction;
6804
7673
  log;
6805
7674
  /** The skills kept in this app's skills folder (`skillsDir`): written by skill_save and the 技能 page. */
6806
7675
  savedSkills;
@@ -6843,6 +7712,7 @@ var AdgGateway = class extends Service {
6843
7712
  return { others: this.instances.others() };
6844
7713
  } }
6845
7714
  }), "adg-gateway capability instances");
7715
+ ctx.effect(() => this.registry.register(aboutCapability()), "adg-gateway capability about");
6846
7716
  this.approvals = new ApprovalBroker({
6847
7717
  broadcastRequested: (request) => this.broadcast("approval/requested", request),
6848
7718
  broadcastResolved: (approvalId, outcome) => this.broadcast("approval/resolved", { approvalId, outcome })
@@ -7311,8 +8181,77 @@ var AdgGateway = class extends Service {
7311
8181
  }), "adg-gateway capability persona");
7312
8182
  this.persona = persona;
7313
8183
  }
8184
+ if (config.dataDir !== void 0) {
8185
+ const memory = new MemoryStore(join7(config.dataDir, "memory.json"), () => this.broadcast("memory/changed", {}));
8186
+ this.memory = memory;
8187
+ const auto = new AutoMemory({
8188
+ store: memory,
8189
+ file: join7(config.dataDir, "memory-auto.json"),
8190
+ read: (sessionId, signal) => this.recentEvents(sessionId, signal),
8191
+ agentOf: (sessionId) => {
8192
+ const spec = this.specOf(sessionId);
8193
+ return spec === void 0 || spec.subAgentOf !== void 0 ? void 0 : { id: spec.id, name: this.persona?.of(spec.id).name ?? spec.name };
8194
+ },
8195
+ defaultModel: () => ctx.get("agentDefaultModel")?.currentSelection(),
8196
+ complete: (request) => this.completeOnce(request),
8197
+ log,
8198
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
8199
+ ...config.memoryIdleMs === void 0 ? {} : { idleMs: config.memoryIdleMs },
8200
+ // Low-context mode compacts all but the last hours: what is worth keeping must be read out first.
8201
+ forced: () => this.compaction?.state().settings.lowContext === true
8202
+ });
8203
+ ctx.effect(() => () => auto.dispose(), "adg-gateway automatic memory");
8204
+ ctx.on("api-session/status", (sessionId, running) => {
8205
+ if (this.isOwn(sessionId))
8206
+ auto.activity(sessionId, running);
8207
+ });
8208
+ ctx.effect(() => this.registry.register({
8209
+ id: MEMORY_CAPABILITY,
8210
+ version: 1,
8211
+ methods: {
8212
+ "memory/list": async () => {
8213
+ await memory.loaded;
8214
+ return { items: memory.list() };
8215
+ },
8216
+ "memory/add": async (params) => {
8217
+ const { kind, scope, text } = params;
8218
+ try {
8219
+ return { item: await memory.add({ kind, scope, text, by: "user" }) };
8220
+ } catch (error) {
8221
+ throw new RpcError(ErrorCode.InvalidParams, error instanceof Error ? error.message : String(error));
8222
+ }
8223
+ },
8224
+ "memory/update": async (params) => {
8225
+ const { id, text, kind, scope } = params;
8226
+ try {
8227
+ return { item: await memory.update(id, { text, ...kind === void 0 ? {} : { kind }, ...scope === void 0 ? {} : { scope } }, "user") };
8228
+ } catch (error) {
8229
+ throw new RpcError(ErrorCode.InvalidParams, error instanceof Error ? error.message : String(error));
8230
+ }
8231
+ },
8232
+ "memory/remove": async (params) => ({ removed: await memory.remove(params.id) }),
8233
+ "memory/auto/get": async () => {
8234
+ await auto.loaded;
8235
+ return { ...auto.settings, ...auto.forced ? { forced: true } : {} };
8236
+ },
8237
+ "memory/auto/set": async (params) => auto.setSettings(params)
8238
+ }
8239
+ }), "adg-gateway capability memory");
8240
+ for (const tool of memoryTools({ store: memory, agentOf: (sessionId) => this.memoryOwner(sessionId), timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone })) {
8241
+ this.agentPart(`adg-gateway ${tool.name}`, (agent) => agent.tools.register(tool));
8242
+ }
8243
+ const history = historyTools({
8244
+ agentOf: (sessionId) => this.memoryOwner(sessionId),
8245
+ sessions: (agent, signal) => this.sessionsOf(agent, signal),
8246
+ read: (sessionId, maxMessages, signal) => this.sessionEvents(sessionId, maxMessages, signal),
8247
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
8248
+ });
8249
+ for (const tool of history)
8250
+ this.agentPart(`adg-gateway ${tool.name}`, (agent) => agent.tools.register(tool));
8251
+ }
7314
8252
  if (config.dataDir !== void 0) {
7315
8253
  const compaction = new CompactionStore(config.dataDir);
8254
+ this.compaction = compaction;
7316
8255
  ctx.effect(() => this.registry.register({
7317
8256
  id: COMPACTION_CAPABILITY,
7318
8257
  version: 1,
@@ -7489,6 +8428,19 @@ Content-Length: 0
7489
8428
  });
7490
8429
  socket.on("error", (error) => log.warn(`socket error: ${error.message}`));
7491
8430
  }
8431
+ /**
8432
+ * Is work of this conversation's task still going elsewhere: a sub-agent of
8433
+ * it working, or work it handed to a colleague not back yet? Low-context mode
8434
+ * (low-context.ts) compacts only once there is none.
8435
+ */
8436
+ workPending(sessionId) {
8437
+ for (const agent of this.agents.values()) {
8438
+ const header = agent.session.header;
8439
+ if (header?.origin === "subagent" && header.parentSession === sessionId && agent.status === "running")
8440
+ return true;
8441
+ }
8442
+ return this.handOffDesk?.waitingOn?.(sessionId) === true;
8443
+ }
7492
8444
  /** Is this one of the app's sessions? Every session is, unless the dsh is shared (Config.shared). */
7493
8445
  isOwn(sessionId) {
7494
8446
  if (!this.shared || this.own.has(sessionId))
@@ -7556,6 +8508,12 @@ Content-Length: 0
7556
8508
  const duty = [spec.duty, spec.subAgentOf === void 0 ? ROLE_CLOSING : void 0].filter((text2) => text2 !== void 0 && text2 !== "").join("\n\n");
7557
8509
  const text = spec === MAIN_AGENT ? () => mainDuty(this.roles.list()) : () => duty;
7558
8510
  disposers.push(agent.ctx.systemPrompt.section({ name: "adg:role", order: 10095, interpolate: false, text }));
8511
+ const memory = this.memory;
8512
+ if (memory !== void 0) {
8513
+ const owner = memoryOwnerOf(spec);
8514
+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
8515
+ disposers.push(agent.ctx.systemPrompt.section({ name: "adg:memory", order: 10098, interpolate: false, text: () => memoryPrompt(memory.visibleTo(owner), owner, { timeZone, ...spec.subAgentOf === void 0 ? {} : { lead: spec.subAgentOf } }) }));
8516
+ }
7559
8517
  if (spec.subAgentOf === void 0) {
7560
8518
  const persona = this.persona;
7561
8519
  const known = (member) => ({ ...member, alias: persona?.of(member.id).name });
@@ -7571,6 +8529,79 @@ Content-Length: 0
7571
8529
  dispose();
7572
8530
  } });
7573
8531
  }
8532
+ /** A session's recent records as protocol events (automatic memory reads them back). */
8533
+ async recentEvents(sessionId, signal) {
8534
+ const controller = new AbortController();
8535
+ const stop = () => controller.abort();
8536
+ signal.addEventListener("abort", stop, { once: true });
8537
+ try {
8538
+ const iterator = this.ctx.sessionController.follow({ address: { kind: "session", sessionId }, maxMessages: 80 }, controller.signal)[Symbol.asyncIterator]();
8539
+ const first = await iterator.next();
8540
+ return first.done === true || first.value.type !== "snapshot" ? [] : convertRecords(first.value.records);
8541
+ } finally {
8542
+ signal.removeEventListener("abort", stop);
8543
+ controller.abort();
8544
+ }
8545
+ }
8546
+ /** An agent's own conversations (not its sub-agents'), newest first. */
8547
+ async sessionsOf(agent, signal) {
8548
+ const { items } = await this.ctx.sessionController.list({}, signal);
8549
+ return items.filter((s) => s.origin !== "subagent" && this.isOwn(String(s.sessionId)) && this.memoryOwner(String(s.sessionId)) === agent).map((s) => ({ id: String(s.sessionId), title: s.projections?.values?.title ?? null, ...typeof s.updatedAt === "number" ? { updatedAt: s.updatedAt } : {} })).sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
8550
+ }
8551
+ /** A session's records as protocol events, oldest first, back to about `maxMessages` messages (history.ts). */
8552
+ async sessionEvents(sessionId, maxMessages, signal) {
8553
+ const controller = new AbortController();
8554
+ const stop = () => controller.abort();
8555
+ signal.addEventListener("abort", stop, { once: true });
8556
+ const address = { kind: "session", sessionId };
8557
+ const PAGE = 400;
8558
+ try {
8559
+ const iterator = this.ctx.sessionController.follow({ address, maxMessages: Math.min(PAGE, maxMessages) }, controller.signal)[Symbol.asyncIterator]();
8560
+ const first = await iterator.next();
8561
+ if (first.done === true || first.value.type !== "snapshot")
8562
+ return [];
8563
+ const snapshot = first.value;
8564
+ let events = convertRecords(snapshot.records);
8565
+ let more = snapshot.hasMore;
8566
+ for (let read = PAGE; more && read < maxMessages && events.length > 0; read += PAGE) {
8567
+ const page = await this.ctx.sessionController.page({ address, throughSeq: snapshot.cursor, beforeSeq: events[0].seq, maxMessages: PAGE }, controller.signal);
8568
+ events = [...convertRecords(page.records), ...events];
8569
+ more = page.hasMore;
8570
+ }
8571
+ return events;
8572
+ } finally {
8573
+ signal.removeEventListener("abort", stop);
8574
+ controller.abort();
8575
+ }
8576
+ }
8577
+ /** One model call outside any conversation, for its text (dsh's llm service). */
8578
+ async completeOnce(request) {
8579
+ const llm = this.ctx.get("llm");
8580
+ if (llm === void 0)
8581
+ throw new Error("no model service");
8582
+ const { provider, model, reasoningEffort } = request.selection;
8583
+ let text = "";
8584
+ for await (const chunk of llm.stream({
8585
+ provider,
8586
+ model,
8587
+ ...reasoningEffort === void 0 ? {} : { reasoningEffort },
8588
+ system: request.system,
8589
+ messages: [{ role: "user", content: [{ type: "text", text: request.prompt }] }],
8590
+ maxTokens: 4e3,
8591
+ signal: request.signal
8592
+ })) {
8593
+ if (chunk.type === "text-delta")
8594
+ text += chunk.text;
8595
+ else if (chunk.type === "finish" && (chunk.reason.kind === "error" || chunk.reason.kind === "aborted"))
8596
+ throw new Error(chunk.reason.failure.message);
8597
+ }
8598
+ return text;
8599
+ }
8600
+ /** Whose memory an agent in this session reads and writes: its own agent's (a sub-agent's lead's); none for other chats. */
8601
+ memoryOwner(sessionId) {
8602
+ const spec = this.specOf(sessionId);
8603
+ return spec === void 0 ? void 0 : memoryOwnerOf(spec);
8604
+ }
7574
8605
  /** The conversation that opened this sub-agent; undefined for any other session. */
7575
8606
  parentSession(sessionId) {
7576
8607
  const header = this.agents.get(sessionId)?.session.header;