mocode-ai 1.8.9 → 1.8.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/index.js +17 -17
- package/dist/agent/model-turn.js +8 -4
- package/dist/agent/run-coordinator.js +6 -0
- package/dist/agent/spawn.js +8 -4
- package/dist/agent/stages/tool-dispatcher.js +31 -11
- package/dist/changeset/hash.js +17 -0
- package/dist/changeset/index.js +6 -10
- package/dist/context/text-search.js +28 -10
- package/dist/flows/cli.js +1 -1
- package/dist/flows/flow.js +1 -1
- package/dist/flows/trace.js +1 -1
- package/dist/headless.js +23 -0
- package/dist/index.js +1 -1
- package/dist/memory/anchor.js +319 -0
- package/dist/memory/audit.js +65 -0
- package/dist/memory/episodic.js +546 -0
- package/dist/memory/graph.js +233 -9
- package/dist/memory/health.js +208 -0
- package/dist/memory/index.js +12 -3
- package/dist/memory/pending.js +269 -0
- package/dist/memory/portable.js +150 -0
- package/dist/memory/proactive.js +588 -0
- package/dist/memory/recall-stats.js +1 -1
- package/dist/memory/reflect.js +260 -6
- package/dist/memory/relation-vocab.js +26 -4
- package/dist/memory/store.js +587 -41
- package/dist/memory/tail.js +88 -0
- package/dist/memory/write-gate.js +44 -0
- package/dist/permissions/computer-review.js +1 -1
- package/dist/permissions/flow-review.js +1 -1
- package/dist/repl/commands/flow.js +1 -1
- package/dist/repl/commands/memory.js +257 -6
- package/dist/repl/commands/session.js +13 -0
- package/dist/repl/commands/tool-group.js +6 -0
- package/dist/repl/episode-finalize.js +55 -0
- package/dist/repl/runtime.js +41 -3
- package/dist/runtime/uia-selector.js +1 -1
- package/dist/runtime/uia-service.js +3 -3
- package/dist/runtime/wait-until.js +1 -1
- package/dist/runtime/window-list.js +1 -1
- package/dist/sandbox/policy.js +49 -0
- package/dist/session/compact.js +47 -12
- package/dist/session/gui-actions.js +1 -1
- package/dist/tools/builtins/computer.js +5 -5
- package/dist/tools/builtins/memory-graph.js +12 -1
- package/dist/tools/builtins/memory-list.js +13 -3
- package/dist/tools/builtins/memory-save.js +82 -2
- package/dist/tools/builtins/memory-search.js +57 -2
- package/dist/tools/builtins/memory-update.js +52 -1
- package/dist/tools/builtins/read-file.js +51 -2
- package/dist/tools/builtins/run-flow.js +1 -1
- package/dist/tools/constants.js +60 -0
- package/package.json +6 -1
package/dist/agent/index.js
CHANGED
|
@@ -299,6 +299,11 @@ onContextUpdate,
|
|
|
299
299
|
toolPolicy,
|
|
300
300
|
/** 仅真实用户 turn 传入;合成 plan 执行轮继承 policy 但不重复记录初始路由。 */
|
|
301
301
|
initialToolRoute,
|
|
302
|
+
/**
|
|
303
|
+
* R17:会话内记忆尾注,由调用方每个用户轮现算(见 memory/tail.ts)。
|
|
304
|
+
* 走 ephemeral 段而非重建 history[0]——后者会让整段对话的前缀缓存每轮失效。
|
|
305
|
+
*/
|
|
306
|
+
memoryTail,
|
|
302
307
|
/** TUI composition root 绑定的 Runtime;旧调用传 AgentRuntimeContext 仍兼容。 */
|
|
303
308
|
runtimeOrContext = defaultRuntime) {
|
|
304
309
|
const runtime = runtimeOrContext instanceof Runtime
|
|
@@ -324,10 +329,8 @@ runtimeOrContext = defaultRuntime) {
|
|
|
324
329
|
// lastChar 镜像:core 跟踪流式末字符决定补换行,但 TUI hooks 需读它决定 layout.contentWrite('\n')。
|
|
325
330
|
// core 的 onTextEnd hook 只在 lastChar !== '\n' 时才调,调后置 '\n';镜像与此同步。
|
|
326
331
|
let lastChar = '';
|
|
327
|
-
// 正文 ->
|
|
328
|
-
//
|
|
329
|
-
// 不能按普通字符串的“两个换行才有一个空行”来计算。
|
|
330
|
-
let textBoundaryNewlines = 0;
|
|
332
|
+
// 正文 -> 工具的边界换行只在流末 onTextEnd 写一次:工具名 delta 可能在正文流到一半时
|
|
333
|
+
// 就先到(网关交错分片),绝不能在 onToolCall 里提前写 \n——那会在词中间封死 markdown 段。
|
|
331
334
|
let hasPendingTextBoundary = false;
|
|
332
335
|
let toolBatchFollowsText = false;
|
|
333
336
|
// Claude 等模型在 tool_calls 前常输出 "Tool results:" 这类无意义叙述。
|
|
@@ -359,7 +362,6 @@ runtimeOrContext = defaultRuntime) {
|
|
|
359
362
|
lastChar = visible[visible.length - 1];
|
|
360
363
|
if (visible.trim().length > 0) {
|
|
361
364
|
hasPendingTextBoundary = true;
|
|
362
|
-
textBoundaryNewlines = 0;
|
|
363
365
|
}
|
|
364
366
|
}
|
|
365
367
|
}
|
|
@@ -402,17 +404,13 @@ runtimeOrContext = defaultRuntime) {
|
|
|
402
404
|
onToolCall: (name) => {
|
|
403
405
|
// 工具调用开始前,先 flush 被抑制的叙述缓冲(若是纯噪声则丢弃)。
|
|
404
406
|
flushPendingNarrationIfAny();
|
|
405
|
-
//
|
|
406
|
-
//
|
|
407
|
-
|
|
407
|
+
// 模型转而生成 tool_call 参数(可能很长,如 write_file 整篇内容):启「生成中」spinner。
|
|
408
|
+
// 此处**不写换行、不封 markdown 段**:工具名 delta 可能在正文流到一半时先到(部分网关
|
|
409
|
+
// 交错下发 content / tool_calls,剩余 content 随后才补完),提前 contentWrite('\n') 会
|
|
410
|
+
// 在词中间硬换行(「d / ispatcher」断词 bug)。只标记「正文后随工具批」,真正的边界换行
|
|
411
|
+
// 由流末 onTextEnd 落、空行归一并到 onToolHeader——那时全部 content 已到齐。
|
|
412
|
+
if (hasPendingTextBoundary)
|
|
408
413
|
toolBatchFollowsText = true;
|
|
409
|
-
if (textBoundaryNewlines < 1) {
|
|
410
|
-
layout.contentWrite('\n');
|
|
411
|
-
}
|
|
412
|
-
lastChar = '\n';
|
|
413
|
-
textBoundaryNewlines = 1;
|
|
414
|
-
hasPendingTextBoundary = false;
|
|
415
|
-
}
|
|
416
414
|
if (name)
|
|
417
415
|
spinner.start(t('agent.generating', { tool: name }));
|
|
418
416
|
},
|
|
@@ -442,20 +440,21 @@ runtimeOrContext = defaultRuntime) {
|
|
|
442
440
|
layout.contentWrite(` ${ui.accent}●${ui.reset} 压缩图片 ${info.replaced} 张转为文字卡(${info.described} 张含描述) 请求体 ${fmt(info.bytesBefore)} → ${fmt(info.bytesAfter)}\n`);
|
|
443
441
|
},
|
|
444
442
|
onTextEnd: () => {
|
|
443
|
+
// 流末正文收尾换行(此刻 content 已全部到齐,不会再出现词中间断行)。
|
|
445
444
|
if (lastChar && lastChar !== '\n') {
|
|
446
445
|
layout.contentWrite('\n');
|
|
447
446
|
lastChar = '\n';
|
|
448
|
-
if (hasPendingTextBoundary)
|
|
449
|
-
textBoundaryNewlines = 1;
|
|
450
447
|
}
|
|
451
448
|
},
|
|
452
449
|
onToolHeader: (tc) => {
|
|
453
450
|
// mutation 的自动展开会把 current/committed 空行状态互相转换;在首摘要真正
|
|
454
451
|
// 落屏前按视觉行归一,避免同样的文本→edit 边界偶发 1 行或 2 行。
|
|
452
|
+
// 普通工具的新建批在 writeToolHeader 内部同样归一,此处只保留 mutation 显式分支。
|
|
455
453
|
if (toolBatchFollowsText && isMutationTool(tc.name, runtime.context.toolRuntime)) {
|
|
456
454
|
layout.normalizeMutationBoundary();
|
|
457
455
|
}
|
|
458
456
|
toolBatchFollowsText = false;
|
|
457
|
+
hasPendingTextBoundary = false;
|
|
459
458
|
writeToolHeader(tc, runtime.context.toolRuntime);
|
|
460
459
|
},
|
|
461
460
|
onToolStart: (name) => spinner.start(t('agent.executing', { tool: name })),
|
|
@@ -509,6 +508,7 @@ runtimeOrContext = defaultRuntime) {
|
|
|
509
508
|
hooks: combinedHooks,
|
|
510
509
|
toolPolicy,
|
|
511
510
|
initialToolRoute,
|
|
511
|
+
memoryTail,
|
|
512
512
|
onTraceEvent: appendCurrentSessionTraceEvent,
|
|
513
513
|
});
|
|
514
514
|
}
|
package/dist/agent/model-turn.js
CHANGED
|
@@ -147,10 +147,11 @@ export async function runModelTurn(input) {
|
|
|
147
147
|
stream.lastChar = text[text.length - 1];
|
|
148
148
|
};
|
|
149
149
|
const onToolCall = (name) => {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
150
|
+
// 注意:不能在这里因工具名到达就发 onTextEnd。部分 OpenAI 兼容网关会在同一响应里
|
|
151
|
+
// 交错下发 content 与 tool_calls delta(文字流到一半先到工具名,后续 content 才补完)。
|
|
152
|
+
// 流中即发 onTextEnd 会让 UI 在词中间硬换行并封死 markdown 段(「继续通读:d / ispatcher」
|
|
153
|
+
// 断词 bug)。onToolCall 此刻只驱动「生成中」spinner;正文收尾换行统一由流末
|
|
154
|
+
// (tool-turn / run-coordinator)依据 stream.lastChar 发一次 onTextEnd,届时全部 content 已到齐。
|
|
154
155
|
hooks.onToolCall?.(name);
|
|
155
156
|
};
|
|
156
157
|
let result;
|
|
@@ -179,6 +180,9 @@ export async function runModelTurn(input) {
|
|
|
179
180
|
'4. Before re-running a search/read you think you already did, check the summary and notes first; repeat only if the result is genuinely missing or the target changed.'
|
|
180
181
|
: '',
|
|
181
182
|
sessionStateText,
|
|
183
|
+
// R17:会话内记忆尾注。放最后——它是最"新"的信息,且每轮可能不同,
|
|
184
|
+
// 放在固定段之后能最大限度保住前缀缓存的可复用部分。
|
|
185
|
+
opts.memoryTail ?? '',
|
|
182
186
|
]
|
|
183
187
|
.filter(Boolean)
|
|
184
188
|
.join('\n\n');
|
|
@@ -44,6 +44,11 @@ import { createLegacyCapabilityResolver, createLegacyTerminationPolicy, createSt
|
|
|
44
44
|
export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
45
45
|
const { history, userInput, signal, hooks } = opts;
|
|
46
46
|
const ctx = opts.runtimeContext ?? defaultAgentRuntimeContext;
|
|
47
|
+
// R3:前摄匹配的上下文取本轮用户文本(纯文本部分)。图片等非文本 part 不参与。
|
|
48
|
+
const proactiveContext = (Array.isArray(userInput) ? userInput : [{ type: 'text', text: userInput }])
|
|
49
|
+
.filter((p) => p.type === 'text')
|
|
50
|
+
.map((p) => p.text)
|
|
51
|
+
.join(' ');
|
|
47
52
|
const runtimeToolSchemas = ctx.toolRuntime.tools.map((tool) => ({
|
|
48
53
|
type: 'function',
|
|
49
54
|
function: {
|
|
@@ -327,6 +332,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
327
332
|
readDedup,
|
|
328
333
|
argumentErrorHint: (name) => argumentErrorHint(name, runtimeContextState),
|
|
329
334
|
...(result.finishReason ? { finishReason: result.finishReason } : {}),
|
|
335
|
+
proactiveContext,
|
|
330
336
|
onToolOutput: (call, chunk) => hooks.onToolOutput?.(call, chunk),
|
|
331
337
|
...(opts.toolPolicy
|
|
332
338
|
? {
|
package/dist/agent/spawn.js
CHANGED
|
@@ -233,16 +233,20 @@ export async function spawnAgent(opts) {
|
|
|
233
233
|
if (s)
|
|
234
234
|
lastChar = s[s.length - 1];
|
|
235
235
|
},
|
|
236
|
-
onToolCall: (
|
|
236
|
+
onToolCall: () => {
|
|
237
|
+
// 不能在工具名到达时就给转写补 \n:网关可能交错下发 content / tool_calls,
|
|
238
|
+
// 工具名先到、正文后补完,提前换行会在词中间断句。换行延迟到 onToolHeader(流已结束)。
|
|
239
|
+
// 子 agent 静默:不启 spinner(name 参数仅主 agent 用)
|
|
240
|
+
},
|
|
241
|
+
onToolHeader: (tc) => {
|
|
242
|
+
// 流末工具头落缓冲前补正文收尾换行(等价主 agent 的 onTextEnd)。
|
|
237
243
|
if (lastChar && lastChar !== '\n') {
|
|
238
244
|
writeBuf('\n');
|
|
239
245
|
lastChar = '\n';
|
|
240
246
|
}
|
|
241
|
-
// 子 agent 静默:不启 spinner(name 参数仅主 agent 用)
|
|
242
|
-
},
|
|
243
|
-
onToolHeader: (tc) => {
|
|
244
247
|
const summary = summarizeToolCall(tc.name, tc.arguments);
|
|
245
248
|
writeBuf(` ● ${tc.name} ${summary}\n`);
|
|
249
|
+
lastChar = '\n';
|
|
246
250
|
// 实时写入主内容区:子 agent 的每次工具调用累计到摘要行计数。
|
|
247
251
|
ensureQuietLine(opts.quietLabel ?? t('skill.executing', { name: opts.prompt.slice(0, 40) }));
|
|
248
252
|
ensureLiveBatch();
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ADD_TOOL_GROUPS_TOOL_NAME } from '../../config/profiles.js';
|
|
2
|
-
import { config } from '../../config/index.js';
|
|
2
|
+
import { config, isMemoryEnabled } from '../../config/index.js';
|
|
3
3
|
import { t } from '../../i18n/index.js';
|
|
4
|
+
import { isProactiveEnabled, proactiveHint } from '../../memory/proactive.js';
|
|
4
5
|
import { checkPermission as defaultCheckPermission } from '../../permissions/index.js';
|
|
5
6
|
import { jailResolve as defaultJailResolve } from '../../sandbox/index.js';
|
|
6
7
|
import { summarizeToolArguments } from '../../session/index.js';
|
|
@@ -23,6 +24,9 @@ class LegacyCompatibleToolDispatcher {
|
|
|
23
24
|
async dispatch(request) {
|
|
24
25
|
const { toolRuntime, checkPermission, jailResolve } = this.dependencies;
|
|
25
26
|
const calls = request.calls;
|
|
27
|
+
// R3.5:每批只判一次开关。memory 总开关 veto 优先于前摄独立开关——用户关掉记忆就不该
|
|
28
|
+
// 再有记忆注入,否则"关闭"只关了一半。
|
|
29
|
+
const proactiveOn = isMemoryEnabled() && isProactiveEnabled();
|
|
26
30
|
const argumentSummaries = calls.map((call) => summarizeToolArguments(call.arguments));
|
|
27
31
|
const orderedResults = new Array(calls.length);
|
|
28
32
|
const modelAttachments = [];
|
|
@@ -42,16 +46,32 @@ class LegacyCompatibleToolDispatcher {
|
|
|
42
46
|
argumentSummary: argumentSummaries[index],
|
|
43
47
|
outcome,
|
|
44
48
|
});
|
|
45
|
-
const execute = (call, hint, onLockAcquired) =>
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
49
|
+
const execute = (call, hint, onLockAcquired) => {
|
|
50
|
+
const pending = toolRuntime.executeToolOutcome(call.name, call.arguments, request.signal, {
|
|
51
|
+
callId: call.id,
|
|
52
|
+
onOutput: (chunk) => request.onToolOutput?.(call, chunk),
|
|
53
|
+
allowedToolNames: request.currentAllowedToolNames(),
|
|
54
|
+
delegation: request.delegation(),
|
|
55
|
+
readDedup: request.readDedup,
|
|
56
|
+
...(hint ? { argumentErrorHint: hint } : {}),
|
|
57
|
+
...(request.finishReason ? { finishReason: request.finishReason } : {}),
|
|
58
|
+
...(onLockAcquired ? { onLockAcquired } : {}),
|
|
59
|
+
});
|
|
60
|
+
if (!proactiveOn)
|
|
61
|
+
return pending;
|
|
62
|
+
// R3.3:前摄注入挂在**这一个**统一出口上,四种调度分支(并行只读 / 编排 / 资源锁 /
|
|
63
|
+
// 串行)自然全覆盖,无须各写一遍。放在 outcome 落地后做:被拒绝或未执行的调用
|
|
64
|
+
// 根本不经过这里,不会白烧一次匹配。
|
|
65
|
+
return pending.then((outcome) => {
|
|
66
|
+
if (outcome.status !== 'success' && outcome.status !== 'error')
|
|
67
|
+
return outcome;
|
|
68
|
+
const proactive = proactiveHint(call.name, parseArgs(call.arguments), true, request.proactiveContext);
|
|
69
|
+
if (!proactive)
|
|
70
|
+
return outcome;
|
|
71
|
+
const base = outcome.output ?? '';
|
|
72
|
+
return { ...outcome, output: base ? `${base}\n\n${proactive}` : proactive };
|
|
73
|
+
});
|
|
74
|
+
};
|
|
55
75
|
const executionEvents = (index, parsed, outcome) => {
|
|
56
76
|
request.onEvent({ type: 'usage', usage: outcome.usage });
|
|
57
77
|
request.onEvent({ type: 'host_outcome', call: calls[index], parsed: parsed ?? {}, outcome });
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// 内容哈希的**唯一实现**。叶子模块:只依赖 node:crypto 与本地类型。
|
|
2
|
+
//
|
|
3
|
+
// 为什么单独拆出来:哈希口径必须全局一致(read_file 的 artifact hash、changeset 的
|
|
4
|
+
// expected_hash、记忆锚点 R2 的 stale 判定都靠它对齐),但 `changeset/index.ts` 会
|
|
5
|
+
// 引入 sandbox/rollback/tools.resource-lock——`memory/store.ts` 是叶模块,不能为了
|
|
6
|
+
// 拿一个 sha256 就把整条工具链依赖拖进来。所以哈希下沉到本文件,changeset/index.ts
|
|
7
|
+
// 改为 re-export,两边字面上是同一个函数对象,口径不可能漂移。
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
export function contentHash(content) {
|
|
10
|
+
const data = typeof content === 'string' ? Buffer.from(content, 'utf8') : content;
|
|
11
|
+
return `sha256:${createHash('sha256').update(data).digest('hex')}`;
|
|
12
|
+
}
|
|
13
|
+
export function normalizeContentHash(value) {
|
|
14
|
+
const normalized = value.trim().toLowerCase();
|
|
15
|
+
const hex = normalized.startsWith('sha256:') ? normalized.slice(7) : normalized;
|
|
16
|
+
return /^[a-f0-9]{64}$/.test(hex) ? `sha256:${hex}` : null;
|
|
17
|
+
}
|
package/dist/changeset/index.js
CHANGED
|
@@ -1,19 +1,15 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { chmod, copyFile, mkdir, readFile, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import { createHash } from 'node:crypto';
|
|
5
4
|
import { jailResolve } from '../sandbox/index.js';
|
|
6
5
|
import { beginPathMutation, endPathMutation } from '../rollback/index.js';
|
|
7
6
|
import { canonicalFileResourceKey, toolResourceLockManager } from '../tools/resource-lock.js';
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
export
|
|
13
|
-
|
|
14
|
-
const hex = normalized.startsWith('sha256:') ? normalized.slice(7) : normalized;
|
|
15
|
-
return /^[a-f0-9]{64}$/.test(hex) ? `sha256:${hex}` : null;
|
|
16
|
-
}
|
|
7
|
+
// 哈希实现已下沉到 ./hash.ts(叶模块):memory/store.ts 要用同一口径算锚点 hash,
|
|
8
|
+
// 但它不能依赖本文件(这里拉着 sandbox/rollback/resource-lock)。re-export 保证
|
|
9
|
+
// 「同一个函数对象」,调用方无需改 import。
|
|
10
|
+
export { contentHash, normalizeContentHash } from './hash.js';
|
|
11
|
+
// re-export 不会把名字带进本模块作用域,内部仍在用 → 单独 import 一次。
|
|
12
|
+
import { contentHash } from './hash.js';
|
|
17
13
|
function applyTextEdits(source, edits) {
|
|
18
14
|
const ordered = [...edits].sort((left, right) => left.start - right.start || left.end - right.end);
|
|
19
15
|
let cursor = 0;
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// 多字段加权 BM25:每个字段独立长度归一,字段分按 weight 加权求和。
|
|
8
8
|
const CJK_RE = /[㐀-䶿一-鿿豈--ヿ가-]/;
|
|
9
9
|
/** CJK 感知分词(小写)。 */
|
|
10
|
-
export function tokenize(input) {
|
|
10
|
+
export function tokenize(input, mode = 'both') {
|
|
11
11
|
const text = (input ?? '').toLowerCase();
|
|
12
12
|
const tokens = [];
|
|
13
13
|
const chars = Array.from(text);
|
|
@@ -26,8 +26,9 @@ export function tokenize(input) {
|
|
|
26
26
|
}
|
|
27
27
|
flushWord();
|
|
28
28
|
if (CJK_RE.test(ch)) {
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
if (mode !== 'bigram')
|
|
30
|
+
tokens.push(ch); // unigram
|
|
31
|
+
if (mode !== 'unigram' && i + 1 < chars.length && CJK_RE.test(chars[i + 1])) {
|
|
31
32
|
tokens.push(ch + chars[i + 1]); // bigram
|
|
32
33
|
}
|
|
33
34
|
}
|
|
@@ -42,9 +43,14 @@ export class TextSearchIndex {
|
|
|
42
43
|
ids;
|
|
43
44
|
fieldStats;
|
|
44
45
|
fieldWeights;
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
46
|
+
mode;
|
|
47
|
+
minEvidence;
|
|
48
|
+
constructor(docs, k1OrOpts = 1.5, b = 0.75) {
|
|
49
|
+
const opts = typeof k1OrOpts === 'number' ? { k1: k1OrOpts, b } : (k1OrOpts ?? {});
|
|
50
|
+
this.k1 = opts.k1 ?? 1.5;
|
|
51
|
+
this.b = opts.b ?? 0.75;
|
|
52
|
+
this.mode = opts.tokenizeMode ?? 'both';
|
|
53
|
+
this.minEvidence = Math.max(0, opts.minEvidenceMatched ?? 0);
|
|
48
54
|
this.ids = docs.map((d) => d.id);
|
|
49
55
|
const fieldCount = Math.max(1, ...docs.map((d) => d.fields.length));
|
|
50
56
|
this.fieldWeights = Array.from({ length: fieldCount }, (_, f) => docs[0]?.fields[f]?.weight ?? 1);
|
|
@@ -57,7 +63,7 @@ export class TextSearchIndex {
|
|
|
57
63
|
docs.forEach((doc, docId) => {
|
|
58
64
|
doc.fields.forEach((field, f) => {
|
|
59
65
|
const stats = this.fieldStats[f];
|
|
60
|
-
const toks = tokenize(field.text);
|
|
66
|
+
const toks = tokenize(field.text, this.mode);
|
|
61
67
|
stats.dl.set(docId, toks.length);
|
|
62
68
|
const seen = new Set();
|
|
63
69
|
for (const t of toks) {
|
|
@@ -83,13 +89,18 @@ export class TextSearchIndex {
|
|
|
83
89
|
}
|
|
84
90
|
/** 检索;无有效查询词时返回空数组(调用方自行决定是否回退全量)。 */
|
|
85
91
|
search(query, limit = 10) {
|
|
86
|
-
const terms = tokenize(query);
|
|
92
|
+
const terms = tokenize(query, this.mode);
|
|
87
93
|
if (terms.length === 0 || this.ids.length === 0)
|
|
88
94
|
return [];
|
|
89
95
|
const n = this.ids.length;
|
|
96
|
+
// 下限的分子:查询里有多少「证据词元」(长度 ≥ 2)。分母与文档无关,先算一次。
|
|
97
|
+
// 查询没有证据词元时(如单字「画」)整条规则退化为不过滤——短查询不该被误杀。
|
|
98
|
+
const evidenceTerms = this.minEvidence > 0 ? [...new Set(terms.filter((t) => t.length >= 2))] : [];
|
|
99
|
+
const needEvidence = evidenceTerms.length === 0 ? 0 : Math.min(this.minEvidence, evidenceTerms.length);
|
|
90
100
|
const hits = [];
|
|
91
101
|
for (let docId = 0; docId < n; docId++) {
|
|
92
102
|
let score = 0;
|
|
103
|
+
const matchedEvidence = needEvidence > 0 ? new Set() : null;
|
|
93
104
|
this.fieldStats.forEach((stats, f) => {
|
|
94
105
|
const dl = stats.dl.get(docId);
|
|
95
106
|
if (dl === undefined)
|
|
@@ -99,13 +110,20 @@ export class TextSearchIndex {
|
|
|
99
110
|
const tf = stats.tf.get(term)?.get(docId);
|
|
100
111
|
if (!tf)
|
|
101
112
|
continue;
|
|
113
|
+
if (matchedEvidence && term.length >= 2)
|
|
114
|
+
matchedEvidence.add(term);
|
|
102
115
|
const df = stats.df.get(term) ?? 0;
|
|
103
116
|
const idf = Math.log(1 + (n - df + 0.5) / (df + 0.5));
|
|
104
117
|
score += ((this.fieldWeights[f] ?? 1) * (idf * (tf * (this.k1 + 1)))) / (tf + norm);
|
|
105
118
|
}
|
|
106
119
|
});
|
|
107
|
-
if (score
|
|
108
|
-
|
|
120
|
+
if (score <= 0)
|
|
121
|
+
continue;
|
|
122
|
+
// 相关性下限:命中证据词元数不够就不算「相关」,无论分数多高。
|
|
123
|
+
// 放在排序前而不是截断后:被过滤的文档不该占 limit 的名额。
|
|
124
|
+
if (needEvidence > 0 && (matchedEvidence?.size ?? 0) < needEvidence)
|
|
125
|
+
continue;
|
|
126
|
+
hits.push({ id: this.ids[docId], score });
|
|
109
127
|
}
|
|
110
128
|
hits.sort((a, b) => b.score - a.score);
|
|
111
129
|
return hits.slice(0, Math.max(1, limit));
|
package/dist/flows/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* `mocode flow list | show <name> | run <name> [k=v ...] [--window <正则>] [--yes] [--sandbox-root <path>]`
|
|
3
|
-
* (design-notes/computer-use-rpa.md §5.4)。
|
|
3
|
+
* (design-notes/computer-use/computer-use-rpa.md §5.4)。
|
|
4
4
|
*
|
|
5
5
|
* 非交互回放入口:不经过模型、不依赖 REPL。权限语义与 `/flow run` 一致但 fail-closed:
|
|
6
6
|
* - 受 Computer Use 总开关否决(MOCODE_COMPUTER_USE_ENABLED=false);
|
package/dist/flows/flow.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* flow 文件:格式、校验、从 trace 导出、参数模板、存取(design-notes/computer-use-rpa.md §5.2)。
|
|
2
|
+
* flow 文件:格式、校验、从 trace 导出、参数模板、存取(design-notes/computer-use/computer-use-rpa.md §5.2)。
|
|
3
3
|
*
|
|
4
4
|
* flow 是 `.mocode/flows/<name>.json`,人可编辑,是回放的唯一事实源。设计要点:
|
|
5
5
|
* - 步骤是扁平对象:保留键(selector/target/fallback/window/allowCoordinateFallback/fragile/onError/note)
|
package/dist/flows/trace.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* computer 动作的结构化录制(design-notes/computer-use-rpa.md §5.1)。
|
|
2
|
+
* computer 动作的结构化录制(design-notes/computer-use/computer-use-rpa.md §5.1)。
|
|
3
3
|
*
|
|
4
4
|
* 与 session/gui-actions.ts 的区别:台账是给模型看的有损文本(24 条滚动);trace 是给 flow 导出用的
|
|
5
5
|
* 结构化 JSONL(`gui-trace.jsonl`,同会话目录),元素动作落盘的是 selector 而不是会过期的 ref。
|
package/dist/headless.js
CHANGED
|
@@ -25,6 +25,9 @@ import { effectiveSystemPrompt } from './skills/index.js';
|
|
|
25
25
|
import { buildMemoryIndexSection, gcMemories } from './memory/store.js';
|
|
26
26
|
import { buildAboutYouSection, initPersona } from './memory/persona.js';
|
|
27
27
|
import { buildProjectGraphHint } from './memory/recall.js';
|
|
28
|
+
import { buildEpisodeSection, collectChangedFiles, extractCompactionSummary, recordSessionEpisode, } from './memory/episodic.js';
|
|
29
|
+
import { flushProactiveStats } from './memory/proactive.js';
|
|
30
|
+
import { writeMemoryHealth } from './memory/health.js';
|
|
28
31
|
import { defaultRuntime, Runtime } from './runtime/index.js';
|
|
29
32
|
import { runAgentCore } from './agent/core.js';
|
|
30
33
|
import { summarizeToolCall, summarizeToolResult } from './ui/render.js';
|
|
@@ -170,6 +173,7 @@ export async function runHeadless(opts) {
|
|
|
170
173
|
const baseConventions = buildBasePrompt(sessionId) +
|
|
171
174
|
buildAboutYouSection(memoryOn) +
|
|
172
175
|
buildMemoryIndexSection(memoryOn) +
|
|
176
|
+
buildEpisodeSection(memoryOn) +
|
|
173
177
|
buildProjectGraphHint(memoryOn);
|
|
174
178
|
const systemContent = botInfo
|
|
175
179
|
? `# Role\n${botInfo.bot.systemPrompt}\n\n` +
|
|
@@ -278,7 +282,26 @@ export async function runHeadless(opts) {
|
|
|
278
282
|
catch {
|
|
279
283
|
// 落盘失败不覆盖主结果
|
|
280
284
|
}
|
|
285
|
+
// R6.1:一次性执行同样落情节——同一个工作区下次跑 `mocode -p` 才知道上次干到哪。
|
|
286
|
+
// 纯本地零 LLM,失败静默(记忆是增强,不能拖垮一次性执行的退出码)。
|
|
287
|
+
if (memoryOn) {
|
|
288
|
+
try {
|
|
289
|
+
recordSessionEpisode({
|
|
290
|
+
sessionId,
|
|
291
|
+
queries: [prompt],
|
|
292
|
+
changedFiles: collectChangedFiles(history),
|
|
293
|
+
summaryText: extractCompactionSummary(history),
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
// best-effort
|
|
298
|
+
}
|
|
299
|
+
}
|
|
281
300
|
closeAllMcp();
|
|
301
|
+
// R4.1:一次性执行同样留下度量 —— 否则 `mocode -p` 用的那一侧永远是空白。
|
|
302
|
+
// 只在前摄计数有增量时才落盘,健康快照失败静默。
|
|
303
|
+
flushProactiveStats();
|
|
304
|
+
writeMemoryHealth(memoryOn);
|
|
282
305
|
await runtime.close();
|
|
283
306
|
if (wt) {
|
|
284
307
|
try {
|
package/dist/index.js
CHANGED
|
@@ -124,7 +124,7 @@ async function main() {
|
|
|
124
124
|
await runConfigWizard();
|
|
125
125
|
process.exit(0);
|
|
126
126
|
}
|
|
127
|
-
// 桌面流程:mocode flow list | show <name> | run <name> ...(不经模型、不进 REPL;design-notes/computer-use-rpa.md §5.4)。
|
|
127
|
+
// 桌面流程:mocode flow list | show <name> | run <name> ...(不经模型、不进 REPL;design-notes/computer-use/computer-use-rpa.md §5.4)。
|
|
128
128
|
if (args[0] === 'flow') {
|
|
129
129
|
const { runFlowCli } = await import('./flows/cli.js');
|
|
130
130
|
const code = await runFlowCli(args.slice(1));
|