nolo-cli 0.8.0-alpha.13 → 0.8.0-alpha.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/{_executeModel-EBU7YBDV.js → _executeModel-KUP2WVMT.js} +14 -14
  2. package/{action-SQGI5JY5.js → action-ZJWE3Y5S.js} +3 -3
  3. package/{addContentAction-ZX2PUS3X.js → addContentAction-TVDBNJM5.js} +2 -2
  4. package/{addDialogAgentAction-ULADQX2Q.js → addDialogAgentAction-EKH774VT.js} +1 -1
  5. package/{agentEmailCommands-IC52LATA.js → agentEmailCommands-VSPS3MZT.js} +14 -14
  6. package/{agentMachineCommands-SFWC6KN4.js → agentMachineCommands-7EK7IKEV.js} +1 -1
  7. package/{agentRecordCommands-VLMLWLCM.js → agentRecordCommands-GYLQ5OA6.js} +14 -14
  8. package/{agentRunCommand-D2PVHUGR.js → agentRunCommand-KL2A7CGA.js} +17 -15
  9. package/{agentSlice-IIC7AISR.js → agentSlice-OEHVCG26.js} +2 -2
  10. package/{authCommand-WXMD3IPR.js → authCommand-PXFX6JDT.js} +8 -1
  11. package/{authCommands-X74AFDTC.js → authCommands-356AYWEK.js} +10 -1
  12. package/chunk-3TZDXYSF.js +71 -0
  13. package/{chunk-7XN726FS.js → chunk-4P3XCCG2.js} +26 -14
  14. package/{chunk-QO4YO77G.js → chunk-63SLEOLK.js} +1 -1
  15. package/{chunk-6XKX2N2E.js → chunk-6GANEXVO.js} +1 -1
  16. package/{chunk-IBJC3GOP.js → chunk-AURGW6TR.js} +1 -1
  17. package/{chunk-7U4TQSWU.js → chunk-AWCQ2SK4.js} +3 -3
  18. package/{chunk-DAB7DRXD.js → chunk-BZMZUAFJ.js} +4 -4
  19. package/{chunk-V2AISYMA.js → chunk-COMXDWNM.js} +1 -1
  20. package/{chunk-YDESHYQC.js → chunk-E7LCFMW5.js} +410 -4
  21. package/{chunk-OF5H3QWS.js → chunk-EXTIQUCI.js} +182 -0
  22. package/{chunk-FE2TZO7Z.js → chunk-FY3KVW36.js} +1 -1
  23. package/{chunk-ZRS4MX3R.js → chunk-HBY2MXIN.js} +20 -18
  24. package/{chunk-6A3LI5TZ.js → chunk-KTVVPRJS.js} +2 -2
  25. package/{chunk-XOH46MRF.js → chunk-M2GJTPUU.js} +4 -4
  26. package/{chunk-ZDXZSXYQ.js → chunk-MGOJ5R6J.js} +1 -1
  27. package/{chunk-3N55DSXH.js → chunk-MTAJCUIC.js} +4 -4
  28. package/{chunk-KH4OXCBK.js → chunk-N5Z5DMDD.js} +2 -2
  29. package/{chunk-Q3K5K4KS.js → chunk-NGXGGF4K.js} +1 -1
  30. package/{chunk-HLM6MG7F.js → chunk-PA23IU5W.js} +7 -7
  31. package/{chunk-CM54RSSA.js → chunk-SL35K7AH.js} +21 -1
  32. package/{chunk-6CBN7GGH.js → chunk-TSS3XJY4.js} +3 -3
  33. package/{chunk-7EPLXPTM.js → chunk-ZJDUYY3D.js} +12 -2
  34. package/{createAgentAutomationAction-GNRYFKTT.js → createAgentAutomationAction-KY7OQ4YJ.js} +6 -6
  35. package/{createDialogAction-Q4ISCARO.js → createDialogAction-CWPWISDF.js} +7 -7
  36. package/{createPageAction-7YCAZPK3.js → createPageAction-GDQVH2DC.js} +6 -6
  37. package/{dbSlice-TO2TSMWM.js → dbSlice-PR44QPXY.js} +1 -1
  38. package/{dialogSlice-5KZA46HM.js → dialogSlice-2EX2IPKM.js} +6 -6
  39. package/{docStore-M7K7QFVS.js → docStore-BDZODEOU.js} +7 -7
  40. package/{handleSendMessageAction-SEV4YIPL.js → handleSendMessageAction-3ZTXMDDU.js} +6 -6
  41. package/index.js +24 -24
  42. package/{machineCommands-T4DN3MOU.js → machineCommands-7PL6UCMC.js} +14 -14
  43. package/{machineWsRunDispatch-QRIIT2AK.js → machineWsRunDispatch-Q6XZLVQE.js} +14 -14
  44. package/package.json +1 -1
  45. package/{readlineWorkspace-DXOTOVHL.js → readlineWorkspace-6S37COYT.js} +17 -15
  46. package/{removeDialogAgentAction-3MUQGFZX.js → removeDialogAgentAction-GJQJNDW6.js} +3 -3
  47. package/{runAgentClientLoop-UEQEP3XG.js → runAgentClientLoop-Y2LTIWEU.js} +12 -12
  48. package/{setDialogExtraReferencesAction-MXHX2HPK.js → setDialogExtraReferencesAction-M7OQG54N.js} +1 -1
  49. package/{setPrimaryDialogAgentAction-7DLDZHDT.js → setPrimaryDialogAgentAction-46UNFJDL.js} +3 -3
  50. package/{settingSlice-PNLASZGI.js → settingSlice-FVUUH4JA.js} +2 -2
  51. package/{spaceSlice-HOMW64JA.js → spaceSlice-ULWMVNFC.js} +6 -6
  52. package/{streamAgentChatTurn-REWDBIL3.js → streamAgentChatTurn-J4YW33EM.js} +15 -15
  53. package/{tools-L4UQS5VW.js → tools-753HRGSD.js} +10 -10
  54. package/{understanding-YH4X3XU6.js → understanding-GQKNDDWM.js} +5 -53
  55. package/{updateDialogTitleAction-CKLNP73H.js → updateDialogTitleAction-PXLE3P4E.js} +6 -6
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  updateContentTitle
3
- } from "./chunk-ZRS4MX3R.js";
3
+ } from "./chunk-HBY2MXIN.js";
4
4
  import {
5
5
  require_date_fns
6
6
  } from "./chunk-M76ECQRD.js";
@@ -13,7 +13,7 @@ import {
13
13
  import {
14
14
  patch,
15
15
  readAndWait
16
- } from "./chunk-V2AISYMA.js";
16
+ } from "./chunk-COMXDWNM.js";
17
17
  import {
18
18
  asOptionalTrimmedString
19
19
  } from "./chunk-G3SUCT4W.js";
@@ -367,7 +367,7 @@ async function saveDocState(arg, { dispatch, getState }) {
367
367
  }
368
368
  }
369
369
  async function createDocState(args, thunkApi) {
370
- const { createPageAction } = await import("./createPageAction-7YCAZPK3.js");
370
+ const { createPageAction } = await import("./createPageAction-GDQVH2DC.js");
371
371
  return createPageAction(args, thunkApi);
372
372
  }
373
373
  function subscribe(listener) {
@@ -8,7 +8,7 @@ import {
8
8
  patch,
9
9
  remove,
10
10
  write
11
- } from "./chunk-V2AISYMA.js";
11
+ } from "./chunk-COMXDWNM.js";
12
12
  import {
13
13
  asRecordOrEmpty
14
14
  } from "./chunk-KX6YBIHG.js";
@@ -289,7 +289,7 @@ var slice = createSliceWithThunks({
289
289
  const overrides = {};
290
290
  if (args.systemPromptOverride !== void 0) overrides.prompt = args.systemPromptOverride;
291
291
  if (args.toolsOverride !== void 0) overrides.tools = args.toolsOverride;
292
- const { _executeModel } = await import("./_executeModel-EBU7YBDV.js");
292
+ const { _executeModel } = await import("./_executeModel-KUP2WVMT.js");
293
293
  return _executeModel(
294
294
  {
295
295
  isStreaming: args.isStreaming ?? false,
@@ -310,7 +310,7 @@ var slice = createSliceWithThunks({
310
310
  * - 循环直到无工具调用或触发其他运行时停止条件
311
311
  */
312
312
  runAgent: create.asyncThunk(async (args, thunkApi) => {
313
- const { runAgentClientLoop } = await import("./runAgentClientLoop-UEQEP3XG.js");
313
+ const { runAgentClientLoop } = await import("./runAgentClientLoop-Y2LTIWEU.js");
314
314
  const { content: loopContent, toolCallCount } = await runAgentClientLoop(
315
315
  {
316
316
  agentKey: args.agentKey,
@@ -326,7 +326,7 @@ var slice = createSliceWithThunks({
326
326
  * 聊天轮次流式 Agent 调用
327
327
  */
328
328
  streamAgentChatTurn: create.asyncThunk(async (args, thunkApi) => {
329
- const { streamAgentChatTurnHandler } = await import("./streamAgentChatTurn-REWDBIL3.js");
329
+ const { streamAgentChatTurnHandler } = await import("./streamAgentChatTurn-J4YW33EM.js");
330
330
  return streamAgentChatTurnHandler(args, thunkApi);
331
331
  }),
332
332
  /**
@@ -748,7 +748,7 @@ var dbSlice = createSliceWithThunks({
748
748
  // 这里改成动态 import,运行期才解析,彻底断开这条边。
749
749
  share: create.asyncThunk(
750
750
  async (config, thunkApi) => {
751
- const { shareResourceAction } = await import("./action-SQGI5JY5.js");
751
+ const { shareResourceAction } = await import("./action-ZJWE3Y5S.js");
752
752
  return shareResourceAction(config, thunkApi);
753
753
  }
754
754
  ),
@@ -16,7 +16,7 @@ import {
16
16
  createCliCallAgentToolExecutor,
17
17
  createCliLocalRuntimeAdapter,
18
18
  isBuiltinNoloAgentRef
19
- } from "./chunk-3N55DSXH.js";
19
+ } from "./chunk-MTAJCUIC.js";
20
20
  import {
21
21
  getReadableCliDb
22
22
  } from "./chunk-W4NVOSFF.js";
@@ -33,24 +33,40 @@ import {
33
33
  } from "./chunk-VHBWHNVT.js";
34
34
  import {
35
35
  applyModelLayerOverride,
36
+ buildMemoryOverlayLayer,
37
+ buildMemoryUseGuidanceLayer,
36
38
  buildModelLayerOverride,
37
39
  buildSkillDiscoveryLayer
38
- } from "./chunk-CM54RSSA.js";
40
+ } from "./chunk-SL35K7AH.js";
39
41
  import {
40
42
  CliProviderQuotaError
41
43
  } from "./chunk-X7W4TNB4.js";
44
+ import {
45
+ resolveMachineId
46
+ } from "./chunk-6HYVJV7B.js";
42
47
  import {
43
48
  isGatewayHttpStatus
44
49
  } from "./chunk-GAKEBQD6.js";
50
+ import {
51
+ buildMemorySubjectsForAgent,
52
+ resolveAgentMemoryPolicy
53
+ } from "./chunk-ZJDUYY3D.js";
45
54
  import {
46
55
  load,
47
56
  parseExternalSkillMarkdown,
48
57
  parseSkillDocProtocol
49
58
  } from "./chunk-ZQ2UM4KG.js";
59
+ import {
60
+ touchMemoryItemsInDb
61
+ } from "./chunk-3TZDXYSF.js";
62
+ import {
63
+ chooseMemoryOwners,
64
+ loadMemoryCandidatesFromDb
65
+ } from "./chunk-Q2YZULBH.js";
50
66
  import {
51
67
  getModelContextWindow,
52
68
  parseUiAskChoiceContent
53
- } from "./chunk-ZRS4MX3R.js";
69
+ } from "./chunk-HBY2MXIN.js";
54
70
  import {
55
71
  readPipeText,
56
72
  spawnProcess
@@ -86,6 +102,9 @@ import {
86
102
  import {
87
103
  toErrorMessage
88
104
  } from "./chunk-HNMXYYJR.js";
105
+ import {
106
+ getDefaultCliLocalRuntimeDb
107
+ } from "./chunk-H33743XH.js";
89
108
  import {
90
109
  parsePositiveFiniteNumberOrFallback
91
110
  } from "./chunk-Y5GCAMGP.js";
@@ -3243,6 +3262,7 @@ async function runLocalAgentTurnForCli(options, settings) {
3243
3262
  noStream: options.noStream,
3244
3263
  ...runtimeContext ? { runtimeContext } : {},
3245
3264
  ...options.extraContextBlocks?.length ? { contextBlocks: options.extraContextBlocks } : {},
3265
+ ...options.contextBlockScopes?.length ? { contextBlockScopes: options.contextBlockScopes } : {},
3246
3266
  ...typeof options.timeoutMs === "number" ? { timeoutMs: options.timeoutMs } : {},
3247
3267
  ...options.actionGateHandler ? { onActionGate: options.actionGateHandler } : {},
3248
3268
  onLoopEvent: (event) => {
@@ -3870,6 +3890,327 @@ ${args.inspection.status.trim()}`] : [],
3870
3890
  ].join("\n");
3871
3891
  }
3872
3892
 
3893
+ // packages/ai/memory/overlay.ts
3894
+ var KIND_TITLES = {
3895
+ episodic: "Episodic",
3896
+ semantic: "Semantic",
3897
+ procedural: "Procedural"
3898
+ };
3899
+ var normalizeDisplayContent = (item) => {
3900
+ const normalized = item.content.trim().replace(/^(你要记住|请记住|以后记住|记住)[,,。.\s::]*/u, "").replace(/[。!?!?]+$/u, "").trim();
3901
+ const stripPrefix = (prefix) => normalized.startsWith(prefix) ? normalized.slice(prefix.length).trim() : normalized;
3902
+ if (item.kind === "semantic") {
3903
+ if (item.tags?.includes("understanding-memory")) {
3904
+ switch (item.facet) {
3905
+ case "unfinished":
3906
+ return `\u7528\u6237\u4ECD\u672A\u5B9A\u4E0B\uFF1A${stripPrefix("\u8FD8\u6CA1\u51B3\u5B9A")}`;
3907
+ case "tension":
3908
+ return `\u7528\u6237\u5F53\u524D\u5728\u6743\u8861\uFF1A${stripPrefix("\u5728\u6743\u8861")}`;
3909
+ case "preference":
3910
+ return `\u7528\u6237\u5F53\u524D\u66F4\u5728\u610F\uFF1A${stripPrefix("\u66F4\u5728\u610F")}`;
3911
+ case "style":
3912
+ return `\u7528\u6237\u4E92\u52A8\u504F\u597D\uFF1A${stripPrefix("\u66F4\u559C\u6B22")}`;
3913
+ case "goal":
3914
+ return `\u7528\u6237\u5F53\u524D\u76EE\u6807\uFF1A${stripPrefix("\u60F3\u63A8\u8FDB")}`;
3915
+ }
3916
+ }
3917
+ return `\u7528\u6237\u957F\u671F\u504F\u597D/\u4E8B\u5B9E\uFF1A${normalized}`;
3918
+ }
3919
+ if (item.kind === "episodic" && (item.patternKey === "explicit-remember" || item.patternKey === "agent-remember")) {
3920
+ return `\u7528\u6237\u660E\u786E\u8981\u6C42\u4F60\u8BB0\u4F4F\uFF1A${normalized}`;
3921
+ }
3922
+ if (item.kind === "episodic" && item.tags?.includes("understanding-memory")) {
3923
+ switch (item.facet) {
3924
+ case "unfinished":
3925
+ return `\u6700\u8FD1\u4E00\u6B21\u5BF9\u8BDD\u663E\u793A\uFF1A\u7528\u6237\u8FD8\u6CA1\u5B9A\u4E0B ${stripPrefix("\u8FD8\u6CA1\u51B3\u5B9A")}`;
3926
+ case "tension":
3927
+ return `\u6700\u8FD1\u4E00\u6B21\u5BF9\u8BDD\u663E\u793A\uFF1A\u7528\u6237\u8FD8\u5728\u6743\u8861 ${stripPrefix("\u5728\u6743\u8861")}`;
3928
+ case "preference":
3929
+ return `\u6700\u8FD1\u4E00\u6B21\u5BF9\u8BDD\u663E\u793A\uFF1A\u7528\u6237\u66F4\u5728\u610F ${stripPrefix("\u66F4\u5728\u610F")}`;
3930
+ case "style":
3931
+ return `\u6700\u8FD1\u4E00\u6B21\u5BF9\u8BDD\u663E\u793A\uFF1A\u7528\u6237\u66F4\u504F\u597D ${stripPrefix("\u66F4\u559C\u6B22")}`;
3932
+ case "goal":
3933
+ return `\u6700\u8FD1\u4E00\u6B21\u5BF9\u8BDD\u663E\u793A\uFF1A\u7528\u6237\u60F3\u63A8\u8FDB ${stripPrefix("\u60F3\u63A8\u8FDB")}`;
3934
+ }
3935
+ }
3936
+ return normalized;
3937
+ };
3938
+ var buildMemoryOverlay = (items) => {
3939
+ if (items.length === 0) return null;
3940
+ const byKind = {
3941
+ episodic: [],
3942
+ semantic: [],
3943
+ procedural: []
3944
+ };
3945
+ for (const item of items) {
3946
+ byKind[item.kind].push(item);
3947
+ }
3948
+ const sections = Object.entries(byKind).filter(([, list]) => list.length > 0).map(([kind, list]) => {
3949
+ const lines = list.slice(0, 3).map((item) => `- ${normalizeDisplayContent(item)}`);
3950
+ return [`[${KIND_TITLES[kind]}]`, ...lines].join("\n");
3951
+ });
3952
+ return [
3953
+ "--- Memory Overlay ---",
3954
+ "\u4EE5\u4E0B\u662F\u5F53\u524D\u8BF7\u6C42\u53EF\u7528\u7684\u8BB0\u5FC6\u4E8B\u5B9E\uFF1B\u76F8\u5173\u65F6\u76F4\u63A5\u57FA\u4E8E\u8FD9\u4E9B\u8BB0\u5FC6\u56DE\u7B54\u3002",
3955
+ "\u7528\u6237\u5F53\u524D\u8F93\u5165\u4F18\u5148\u4E8E\u8BB0\u5FC6\uFF1B\u8BB0\u5FC6\u53EA\u8F85\u52A9\u7406\u89E3\uFF0C\u4E0D\u8981\u6C42\u8FCE\u5408\u3002",
3956
+ "",
3957
+ ...sections
3958
+ ].join("\n");
3959
+ };
3960
+
3961
+ // packages/ai/memory/rank.ts
3962
+ var CJK_SEQUENCE_REGEX = /[\u3400-\u4dbf\u4e00-\u9fff]+/g;
3963
+ var MEMORY_IDENTIFIER_REGEX = /\b(?:memory|noise)-[a-z0-9][a-z0-9-]*/gi;
3964
+ var buildCjkTokens = (text) => {
3965
+ const sequences = text.match(CJK_SEQUENCE_REGEX) ?? [];
3966
+ const tokens = [];
3967
+ for (const sequence of sequences) {
3968
+ if (sequence.length >= 2) {
3969
+ tokens.push(sequence);
3970
+ }
3971
+ for (let index = 0; index < sequence.length - 1; index += 1) {
3972
+ tokens.push(sequence.slice(index, index + 2));
3973
+ }
3974
+ }
3975
+ return tokens;
3976
+ };
3977
+ var tokenize = (text) => {
3978
+ const normalized = text.toLowerCase();
3979
+ const wordTokens = normalized.split(/[\s,.;:!?()[\]{}"'`,。!?:;、]+/).map((token) => token.trim()).filter((token) => token.length >= 2);
3980
+ return [...wordTokens, ...buildCjkTokens(normalized)];
3981
+ };
3982
+ var keywordScore = (query, item) => {
3983
+ const queryTokens = new Set(tokenize(query));
3984
+ if (queryTokens.size === 0) return 0;
3985
+ const haystack = /* @__PURE__ */ new Set([
3986
+ ...tokenize(item.content),
3987
+ ...(item.tags ?? []).map((tag) => tag.toLowerCase()),
3988
+ item.patternKey?.toLowerCase() ?? ""
3989
+ ]);
3990
+ let matches = 0;
3991
+ for (const token of queryTokens) {
3992
+ if (haystack.has(token)) matches += 1;
3993
+ }
3994
+ return Math.min(1, matches / Math.max(2, queryTokens.size));
3995
+ };
3996
+ var identifierScore = (query, item) => {
3997
+ const identifiers = query.match(MEMORY_IDENTIFIER_REGEX) ?? [];
3998
+ if (identifiers.length === 0) return 0;
3999
+ const content = item.content.toLowerCase();
4000
+ const matches = identifiers.filter(
4001
+ (identifier) => content.includes(identifier.toLowerCase())
4002
+ ).length;
4003
+ return matches / identifiers.length;
4004
+ };
4005
+ var activationScore = (item, nowMs) => {
4006
+ const lastActivatedMs = Date.parse(item.lastActivatedAt || item.createdAt);
4007
+ const ageDays = Math.max(0, (nowMs - lastActivatedMs) / 864e5);
4008
+ const recency = 1 / (1 + ageDays / 7);
4009
+ const reinforcement = Math.min(1, Math.log1p(item.activationCount ?? 0) / 3);
4010
+ return 0.7 * recency + 0.3 * reinforcement;
4011
+ };
4012
+ var creationRecencyScore = (item, nowMs) => {
4013
+ const createdMs = Date.parse(item.createdAt);
4014
+ const ageDays = Math.max(0, (nowMs - createdMs) / 864e5);
4015
+ return 1 / (1 + ageDays / 7);
4016
+ };
4017
+ var typeFitScore = (item) => {
4018
+ if (item.kind === "episodic") return 0.75;
4019
+ if (item.kind === "semantic") return 0.9;
4020
+ return 0.85;
4021
+ };
4022
+ var understandingScore = (item) => {
4023
+ if (!item.tags?.includes("understanding-memory")) return 0;
4024
+ if (item.facet === "unfinished") return 1;
4025
+ if (item.facet === "tension") return 0.95;
4026
+ if (item.facet === "preference") return 0.85;
4027
+ if (item.facet === "style") return 0.75;
4028
+ return 0.8;
4029
+ };
4030
+ var pathScore = (item, context) => {
4031
+ let score = 0;
4032
+ if (context?.currentOwner && item.ownerType === context.currentOwner.ownerType && item.ownerId === context.currentOwner.ownerId) {
4033
+ score += 0.65;
4034
+ }
4035
+ if (context?.currentSubject && item.subjectType === context.currentSubject.subjectType && item.subjectId === context.currentSubject.subjectId) {
4036
+ score += 0.85;
4037
+ }
4038
+ return Math.min(1, score);
4039
+ };
4040
+ var scoreMemoryItem = (item, query, nowMs = Date.now(), context) => {
4041
+ const queryMatch = keywordScore(query, item);
4042
+ const identifierMatch = identifierScore(query, item);
4043
+ const activation = activationScore(item, nowMs);
4044
+ const createdRecency = creationRecencyScore(item, nowMs);
4045
+ const importance = item.importance ?? 0;
4046
+ const confidence = item.confidence ?? 0;
4047
+ const typeFit = typeFitScore(item);
4048
+ const understanding = understandingScore(item);
4049
+ const path = pathScore(item, context);
4050
+ return 0.25 * queryMatch + 0.2 * identifierMatch + 0.2 * path + 0.09 * activation + 0.16 * createdRecency + 0.06 * importance + 0.03 * confidence + 0.02 * typeFit + 0.01 * understanding;
4051
+ };
4052
+ var rankMemoryCandidates = (items, query, context) => {
4053
+ const nowMs = Date.now();
4054
+ return [...items].sort((a, b) => {
4055
+ const aExplicit = a.sourceKind === "explicit-user-directive";
4056
+ const bExplicit = b.sourceKind === "explicit-user-directive";
4057
+ if (aExplicit !== bExplicit) return bExplicit ? 1 : -1;
4058
+ if (aExplicit) {
4059
+ return Date.parse(b.createdAt) - Date.parse(a.createdAt);
4060
+ }
4061
+ return scoreMemoryItem(b, query, nowMs, context) - scoreMemoryItem(a, query, nowMs, context);
4062
+ });
4063
+ };
4064
+
4065
+ // packages/ai/memory/runtime.ts
4066
+ var COLD_STORAGE_CONFIDENCE = 0.3;
4067
+ var normalizeSelectedContent = (text) => text.trim().replace(/^(你要记住|请记住|以后记住|记住)[,,。.\s::]*/u, "").replace(/[。!?!?]+$/u, "").trim();
4068
+ var STACK_TERMS = [
4069
+ "typescript",
4070
+ "javascript",
4071
+ "python",
4072
+ "rust",
4073
+ "go",
4074
+ "golang",
4075
+ "java",
4076
+ "kotlin",
4077
+ "swift",
4078
+ "ruby",
4079
+ "php"
4080
+ ];
4081
+ var stackAliases = {
4082
+ golang: "go"
4083
+ };
4084
+ var normalizeStackTerm = (term) => stackAliases[term] ?? term;
4085
+ var stackTermsIn = (text) => {
4086
+ const lower = text.toLowerCase();
4087
+ const terms = /* @__PURE__ */ new Set();
4088
+ for (const term of STACK_TERMS) {
4089
+ const pattern = term.length <= 2 ? new RegExp(`\\b${term}\\b`, "i") : new RegExp(term, "i");
4090
+ if (pattern.test(lower)) {
4091
+ terms.add(normalizeStackTerm(term));
4092
+ }
4093
+ }
4094
+ return terms;
4095
+ };
4096
+ var conflictsWithCurrentStack = (item, userInput) => {
4097
+ const currentStacks = stackTermsIn(userInput);
4098
+ if (currentStacks.size === 0) return false;
4099
+ const memoryStacks = stackTermsIn(item.content);
4100
+ if (memoryStacks.size === 0) return false;
4101
+ for (const stack of memoryStacks) {
4102
+ if (!currentStacks.has(stack)) return true;
4103
+ }
4104
+ return false;
4105
+ };
4106
+ var INTERACTION_PREFERENCE_TERMS = [
4107
+ "\u56DE\u7B54\u504F\u597D",
4108
+ "\u8F93\u51FA\u504F\u597D",
4109
+ "\u56DE\u590D\u504F\u597D",
4110
+ "\u56DE\u7B54\u7ED3\u6784",
4111
+ "\u8F93\u51FA\u7ED3\u6784",
4112
+ "\u56DE\u590D\u7ED3\u6784",
4113
+ "\u5148\u7ED9\u7ED3\u8BBA",
4114
+ "\u518D\u5217\u98CE\u9669",
4115
+ "\u6700\u540E\u7ED9\u8BC1\u636E",
4116
+ "\u8BED\u6C14",
4117
+ "\u98CE\u683C",
4118
+ "\u79F0\u547C",
4119
+ "\u53EB\u6211"
4120
+ ];
4121
+ var isInteractionPreferenceMemory = (item) => {
4122
+ if (item.facet === "style") return true;
4123
+ const content = normalizeSelectedContent(item.content);
4124
+ return INTERACTION_PREFERENCE_TERMS.some((term) => content.includes(term));
4125
+ };
4126
+ var isOffCurrentPath = (item, context) => {
4127
+ const currentOwner = context?.currentOwner;
4128
+ const currentSubject = context?.currentSubject;
4129
+ if (currentSubject && (item.subjectType === "project" || item.subjectType === "space") && item.subjectType === currentSubject.subjectType && item.subjectId !== currentSubject.subjectId) {
4130
+ return true;
4131
+ }
4132
+ if (currentOwner?.ownerType === "space" && item.ownerType === "user" && (item.subjectType === "project" || item.subjectType === "space") && item.subjectId !== currentOwner.ownerId) {
4133
+ return true;
4134
+ }
4135
+ return false;
4136
+ };
4137
+ var selectRuntimeMemoryItems = (items, context, userInput = "") => {
4138
+ const seen = /* @__PURE__ */ new Set();
4139
+ const unique = items.filter((item) => {
4140
+ if ((item.confidence ?? 0) < COLD_STORAGE_CONFIDENCE) return false;
4141
+ if (isOffCurrentPath(item, context)) return false;
4142
+ if (conflictsWithCurrentStack(item, userInput)) return false;
4143
+ const key = `${item.kind}:${normalizeSelectedContent(item.content).toLowerCase()}`;
4144
+ if (seen.has(key)) return false;
4145
+ seen.add(key);
4146
+ return true;
4147
+ });
4148
+ const selected = [];
4149
+ const selectedIds = /* @__PURE__ */ new Set();
4150
+ const add = (item) => {
4151
+ if (!item || selectedIds.has(item.id) || selected.length >= 4) return;
4152
+ selected.push(item);
4153
+ selectedIds.add(item.id);
4154
+ };
4155
+ add(
4156
+ unique.find(
4157
+ (item) => context?.currentSubject && item.subjectType === context.currentSubject.subjectType && item.subjectId === context.currentSubject.subjectId
4158
+ )
4159
+ );
4160
+ add(unique.find(isInteractionPreferenceMemory));
4161
+ add(
4162
+ unique.find(
4163
+ (item) => context?.currentOwner && item.ownerType === context.currentOwner.ownerType && item.ownerId === context.currentOwner.ownerId
4164
+ )
4165
+ );
4166
+ add(unique.find((item) => item.ownerType === "user"));
4167
+ add(unique.find((item) => item.ownerType === "space"));
4168
+ add(unique.find((item) => item.kind === "procedural"));
4169
+ for (const item of unique) {
4170
+ add(item);
4171
+ }
4172
+ return selected;
4173
+ };
4174
+ var resolveMemoryRuntime = async (input) => {
4175
+ const owners = chooseMemoryOwners({
4176
+ userId: input.userId,
4177
+ spaceId: input.spaceId
4178
+ });
4179
+ if (owners.length === 0) {
4180
+ return { selectedItems: [], promptBlock: null };
4181
+ }
4182
+ const policy = resolveAgentMemoryPolicy({ agentKey: input.agentKey });
4183
+ const candidates = await loadMemoryCandidatesFromDb(input.db, {
4184
+ owners,
4185
+ subjects: buildMemorySubjectsForAgent({
4186
+ userId: input.userId,
4187
+ spaceId: input.spaceId,
4188
+ agentKey: input.agentKey,
4189
+ policy
4190
+ }),
4191
+ kinds: ["episodic", "semantic", "procedural"],
4192
+ ownerLimit: 20,
4193
+ ownerFallback: policy.ownerFallback
4194
+ });
4195
+ const rankContext = {
4196
+ currentOwner: input.spaceId ? { ownerType: "space", ownerId: input.spaceId } : input.userId ? { ownerType: "user", ownerId: input.userId } : null,
4197
+ currentSubject: input.spaceId ? { subjectType: "space", subjectId: input.spaceId } : input.userId ? { subjectType: "user", subjectId: input.userId } : null
4198
+ };
4199
+ const ranked = selectRuntimeMemoryItems(
4200
+ rankMemoryCandidates(candidates, input.userInput, rankContext),
4201
+ rankContext,
4202
+ input.userInput
4203
+ );
4204
+ if (ranked.length === 0) {
4205
+ return { selectedItems: [], promptBlock: null };
4206
+ }
4207
+ await touchMemoryItemsInDb(input.db, ranked);
4208
+ return {
4209
+ selectedItems: ranked,
4210
+ promptBlock: buildMemoryOverlay(ranked)
4211
+ };
4212
+ };
4213
+
3873
4214
  // packages/cli/agentRunCommand.ts
3874
4215
  function resolvePositiveMs(value, fallback) {
3875
4216
  return parsePositiveFiniteNumberOrFallback(value, fallback);
@@ -4152,6 +4493,70 @@ ${mdContent}`);
4152
4493
  if (skillDiscoveryBlock) {
4153
4494
  extraContextBlocks.push(skillDiscoveryBlock);
4154
4495
  }
4496
+ let memoryPromptBlock = null;
4497
+ if (!deps.memoryRecallDisabled) {
4498
+ const memoryServerUrl = resolveServerUrl(env);
4499
+ const memoryAuthToken = resolveAuthToken(args, env);
4500
+ const memoryAgentKey = effectiveAgentKey;
4501
+ const memorySpaceId = parsed.spaceId ?? void 0;
4502
+ try {
4503
+ if (memoryAuthToken && memoryServerUrl) {
4504
+ const memoryResponse = await fetch(`${memoryServerUrl}/api/memory/query`, {
4505
+ method: "POST",
4506
+ headers: {
4507
+ "Content-Type": "application/json",
4508
+ Authorization: `Bearer ${memoryAuthToken}`
4509
+ },
4510
+ body: JSON.stringify({
4511
+ agentKey: memoryAgentKey,
4512
+ userInput: effectiveMessage,
4513
+ ...memorySpaceId ? { spaceId: memorySpaceId } : {}
4514
+ }),
4515
+ signal: AbortSignal.timeout(5e3)
4516
+ });
4517
+ if (memoryResponse.ok) {
4518
+ const memoryPayload = await memoryResponse.json().catch(() => null);
4519
+ const block = typeof memoryPayload?.promptBlock === "string" ? memoryPayload.promptBlock.trim() : "";
4520
+ memoryPromptBlock = block || null;
4521
+ } else {
4522
+ console.warn("[cli-memory] memory query returned non-ok status:", memoryResponse.status);
4523
+ }
4524
+ } else {
4525
+ const localDb = await getDefaultCliLocalRuntimeDb({ env });
4526
+ const machineId = resolveMachineId();
4527
+ const resolution = await resolveMemoryRuntime({
4528
+ db: localDb,
4529
+ userId: machineId,
4530
+ agentKey: memoryAgentKey,
4531
+ userInput: effectiveMessage,
4532
+ ...memorySpaceId ? { spaceId: memorySpaceId } : {}
4533
+ });
4534
+ memoryPromptBlock = resolution.promptBlock;
4535
+ }
4536
+ } catch (memoryError) {
4537
+ console.warn("[cli-memory] memory recall failed, omitting memory layer:", memoryError);
4538
+ }
4539
+ }
4540
+ const memoryOverlayLayer = buildMemoryOverlayLayer({ promptBlock: memoryPromptBlock });
4541
+ const memoryUseGuidanceLayer = buildMemoryUseGuidanceLayer({ promptBlock: memoryPromptBlock });
4542
+ const contextBlockScopes = [];
4543
+ const agentsMdMarker = "--- \u9879\u76EE\u6307\u4EE4\uFF08";
4544
+ for (const block of extraContextBlocks) {
4545
+ if (block.startsWith(agentsMdMarker)) {
4546
+ contextBlockScopes.push({ content: block, cacheScope: "session" });
4547
+ }
4548
+ }
4549
+ if (memoryUseGuidanceLayer?.content?.trim()) {
4550
+ contextBlockScopes.push({ content: memoryUseGuidanceLayer.content, cacheScope: "session" });
4551
+ }
4552
+ for (const block of extraContextBlocks) {
4553
+ if (!block.startsWith(agentsMdMarker)) {
4554
+ contextBlockScopes.push({ content: block, cacheScope: "turn" });
4555
+ }
4556
+ }
4557
+ if (memoryOverlayLayer?.content?.trim()) {
4558
+ contextBlockScopes.push({ content: memoryOverlayLayer.content, cacheScope: "turn" });
4559
+ }
4155
4560
  const buildRunOptions = (targetAgentKey) => ({
4156
4561
  agentName: targetAgentKey,
4157
4562
  agentKey: targetAgentKey,
@@ -4192,7 +4597,8 @@ ${mdContent}`);
4192
4597
  traceTools: parsed.traceTools,
4193
4598
  ...parsed.eventsMode ? { eventsMode: parsed.eventsMode } : {},
4194
4599
  ...parsed.taskEvidence ? { taskEvidence: parsed.taskEvidence } : {},
4195
- ...extraContextBlocks.length > 0 ? { extraContextBlocks } : {}
4600
+ ...extraContextBlocks.length > 0 ? { extraContextBlocks } : {},
4601
+ ...contextBlockScopes.length > 0 ? { contextBlockScopes } : {}
4196
4602
  });
4197
4603
  let result = await raceWithWatchdog(
4198
4604
  runner({