evolcore 0.0.39 → 0.0.41-test.0
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/CHANGELOG.md +93 -0
- package/README.md +31 -20
- package/bin/codex-managed-hook.mjs +11 -0
- package/bin/ec-safe-output.js +25 -3
- package/dist/agents/baseagent-availability.js +1 -0
- package/dist/agents/claude-runner.js +53 -152
- package/dist/agents/codex-runner.js +485 -241
- package/dist/agents/ecagent-runner.js +48 -18
- package/dist/agents/gemini-runner.js +27 -8
- package/dist/agents/runner-types.js +39 -9
- package/dist/aun/ability-device-routing.js +26 -0
- package/dist/aun/aid/client.js +1 -1
- package/dist/aun/aid/control-aid.js +23 -98
- package/dist/aun/aid/ownership-operation.js +1 -3
- package/dist/aun/group/identity.js +8 -0
- package/dist/aun/group/invite-service.js +6 -0
- package/dist/aun/msg/managed-operation.js +4 -4
- package/dist/aun/msg/p2p.js +28 -12
- package/dist/aun/storage/download.js +30 -0
- package/dist/aun/storage/index.js +14 -6
- package/dist/channels/aun.js +99 -52
- package/dist/channels/daemon.js +24 -4
- package/dist/channels/dingtalk.js +8 -2
- package/dist/channels/feishu.js +6 -1
- package/dist/channels/wecom.js +7 -3
- package/dist/cli/agent-command.js +2 -0
- package/dist/cli/agent-create.js +121 -23
- package/dist/cli/agent.js +10 -3
- package/dist/cli/aid-bind-command.js +4 -1
- package/dist/cli/aun-commands.js +82 -22
- package/dist/cli/daemon-commands.js +260 -26
- package/dist/cli/index.js +25 -13
- package/dist/cli/memory-command.js +33 -14
- package/dist/cli/restart-monitor.js +52 -13
- package/dist/cli/session-command.js +128 -13
- package/dist/cli/stats.js +60 -4
- package/dist/cli/task-context.js +1 -0
- package/dist/cli/trigger-command.js +2 -2
- package/dist/config/access-policy.js +2 -0
- package/dist/config/config-field-policy.js +1 -0
- package/dist/config/config-operation-service.js +17 -6
- package/dist/config/gateway-config.js +1 -1
- package/dist/config/peer-role-resolver.js +10 -8
- package/dist/contracts/ecweb-service-protocol.js +44 -0
- package/dist/core/agent-application-service.js +11 -1
- package/dist/core/agent-ipc-registration.js +4 -0
- package/dist/core/agent-runtime.js +6 -0
- package/dist/core/auth/agent-delegation.js +87 -9
- package/dist/core/auth/auth-gateway.js +3 -1
- package/dist/core/auth/authorization-audit.js +25 -4
- package/dist/core/auth/debug-context.js +5 -1
- package/dist/core/auth/operation-catalog.js +24 -0
- package/dist/core/command/agent-control.js +91 -12
- package/dist/core/command/command-handler.js +64 -47
- package/dist/core/command/connect-menu.js +23 -2
- package/dist/core/command/menu-catalog.js +49 -12
- package/dist/core/command/menu-handler.js +110 -105
- package/dist/core/command/menu-protocol.js +29 -3
- package/dist/core/command/role-menu.js +7 -6
- package/dist/core/command/slash-gate.js +22 -5
- package/dist/core/command/slash-handler.js +121 -102
- package/dist/core/event-catalog.js +17 -0
- package/dist/core/interaction-router.js +2 -1
- package/dist/core/ipc-registration.js +44 -8
- package/dist/core/memory/batch-meta.js +2 -0
- package/dist/core/memory/consolidation-context.js +42 -51
- package/dist/core/memory/consolidation-ops-records.js +39 -7
- package/dist/core/memory/consolidation-trigger.js +72 -65
- package/dist/core/memory/consolidation.js +226 -20
- package/dist/core/memory/memory-writer.js +160 -34
- package/dist/core/memory/relation-idle-monitor.js +287 -0
- package/dist/core/memory/relation-sweep.js +206 -0
- package/dist/core/message/aun-ipc-sender.js +31 -5
- package/dist/core/message/aun-request-registry.js +97 -3
- package/dist/core/message/im-renderer.js +4 -0
- package/dist/core/message/message-admission.js +8 -4
- package/dist/core/message/message-bridge.js +96 -53
- package/dist/core/message/message-log.js +72 -0
- package/dist/core/message/message-queue.js +11 -5
- package/dist/core/message/outbound.js +70 -0
- package/dist/core/message/peer-mode.js +7 -2
- package/dist/core/message/response-engine.js +633 -191
- package/dist/core/model/model-catalog.js +7 -6
- package/dist/core/ownership/owner-resolver.js +384 -178
- package/dist/core/permission/ec-command-parser.js +129 -8
- package/dist/core/permission/tool-policy.js +35 -14
- package/dist/core/role/runtime-policy.js +64 -0
- package/dist/core/session/session-capsule.js +197 -0
- package/dist/core/session/session-manager.js +172 -18
- package/dist/core/session/session-mapper.js +2 -0
- package/dist/core/system-session/memory.js +3 -18
- package/dist/ecweb/basic-settings-service.js +709 -0
- package/dist/ecweb/providers-service.js +172 -0
- package/dist/index.js +95 -7
- package/dist/ipc.js +100 -19
- package/dist/stats/budget.js +1 -1
- package/dist/stats/db.js +48 -0
- package/dist/stats/index.js +3 -3
- package/dist/stats/price-resolver.js +304 -5
- package/dist/stats/query.js +328 -3
- package/dist/stats/writer.js +79 -6
- package/dist/trigger/application-service.js +12 -0
- package/dist/trigger/authorization.js +2 -2
- package/dist/trigger/feedback.js +18 -7
- package/dist/trigger/history.js +36 -0
- package/dist/trigger/manager.js +20 -3
- package/dist/trigger/parser.js +6 -3
- package/dist/trigger/patch.js +1 -1
- package/dist/trigger/scheduler.js +3 -0
- package/dist/trigger/system-definitions.js +43 -7
- package/dist/trigger/validation.js +13 -5
- package/dist/utils/ecweb-supervisor.js +31 -10
- package/dist/utils/error-utils.js +22 -4
- package/dist/utils/evolcore-version.js +3 -2
- package/dist/utils/host-info.js +52 -0
- package/dist/utils/npm-ops.js +2 -1
- package/dist/utils/package-version-info.js +1 -1
- package/dist/utils/upgrade-jobs.js +45 -5
- package/ecagent/dist/harness/agent-harness.js +4 -1
- package/kits/docs/INDEX.md +1 -1
- package/kits/docs/aun/ABILITY_CALLING.md +20 -2
- package/kits/docs/evolcore/INDEX.md +3 -2
- package/kits/docs/evolcore/agent-create.md +3 -2
- package/kits/docs/evolcore/agent.md +1 -1
- package/kits/docs/evolcore/aid.md +29 -12
- package/kits/docs/evolcore/config.md +9 -7
- package/kits/docs/evolcore/event.md +1 -0
- package/kits/docs/evolcore/fs.md +5 -0
- package/kits/docs/evolcore/memory-architecture.md +3 -4
- package/kits/docs/evolcore/memory-consolidation.md +28 -7
- package/kits/docs/evolcore/memory-tags.md +1 -1
- package/kits/docs/evolcore/memory.md +1 -1
- package/kits/docs/evolcore/menu-client.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +38 -0
- package/kits/docs/evolcore/msg.md +18 -2
- package/kits/docs/evolcore/session.md +14 -0
- package/kits/eck_manifest.json +3 -3
- package/kits/rules/04-relation.md +3 -2
- package/kits/schemas/agent-config.schema.13.json +20 -1
- package/kits/skills/aid-ability/SKILL.md +35 -6
- package/kits/templates/memory-consolidation/generalize.md +32 -4
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/promote.md +10 -2
- package/kits/templates/session-capsule/recovery.md +5 -0
- package/kits/templates/session-capsule/renew.md +5 -0
- package/kits/templates/system-fragments/baseagent.md +5 -0
- package/kits/templates/system-fragments/bootstrap.md +6 -6
- package/kits/templates/system-fragments/channel.md +1 -1
- package/kits/templates/system-fragments/memory.md +12 -3
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/{rules/07-memory-and-thread.md → templates/system-fragments/thread.md} +17 -80
- package/package.json +3 -3
- package/dist/stats/billing.js +0 -215
|
@@ -24,6 +24,29 @@ export function parseJsonObjectArgument(raw, optionName = '--payload') {
|
|
|
24
24
|
}
|
|
25
25
|
return parsed;
|
|
26
26
|
}
|
|
27
|
+
export function buildCanonicalEvolcoreExecutionSpec(input) {
|
|
28
|
+
const spec = {
|
|
29
|
+
version: 1,
|
|
30
|
+
dialect: input.dialect,
|
|
31
|
+
wrapper: input.wrapper,
|
|
32
|
+
argv: normalizeEvolcoreCommandArgv(input.argv),
|
|
33
|
+
};
|
|
34
|
+
if (input.cwd !== undefined)
|
|
35
|
+
spec.cwd = input.cwd;
|
|
36
|
+
if (input.command?.mergeStderr)
|
|
37
|
+
spec.mergeStderr = true;
|
|
38
|
+
if (input.command?.filterChain?.length)
|
|
39
|
+
spec.filterChain = input.command.filterChain.map(stage => [...stage]);
|
|
40
|
+
if (input.command?.suffixArgv?.length)
|
|
41
|
+
spec.suffixArgv = [...input.command.suffixArgv];
|
|
42
|
+
if (input.command?.outputPath)
|
|
43
|
+
spec.outputPath = input.command.outputPath;
|
|
44
|
+
return spec;
|
|
45
|
+
}
|
|
46
|
+
/** Stable JSON used in delegation metadata and diagnostics. */
|
|
47
|
+
export function serializeCanonicalEvolcoreExecutionSpec(spec) {
|
|
48
|
+
return JSON.stringify(spec);
|
|
49
|
+
}
|
|
27
50
|
function parseApplyPatchCommand(command, options = {}) {
|
|
28
51
|
const input = command.trim();
|
|
29
52
|
let commandText = input;
|
|
@@ -185,6 +208,9 @@ const STDOUT_FILTER_SPECS = new Map([
|
|
|
185
208
|
// operand. Once an explicit pattern option appears, a bare operand would be
|
|
186
209
|
// a file to read, so the operand budget drops to zero. `-r`/`-R`/`-f` are
|
|
187
210
|
// absent from both tables, which keeps recursion and pattern files out.
|
|
211
|
+
// `-d recurse` is the same recursion as `-r` and makes grep ignore stdin and
|
|
212
|
+
// read the working directory, so `-d`/`--directories` are absent too, along
|
|
213
|
+
// with `--include`/`--exclude`/`--exclude-dir`, which only act on recursion.
|
|
188
214
|
['grep', {
|
|
189
215
|
flags: new Set([
|
|
190
216
|
'-i', '--ignore-case', '-v', '--invert-match', '-c', '--count',
|
|
@@ -198,7 +224,7 @@ const STDOUT_FILTER_SPECS = new Map([
|
|
|
198
224
|
valueOptions: new Set([
|
|
199
225
|
'-m', '--max-count', '-A', '--after-context', '-B', '--before-context',
|
|
200
226
|
'-C', '--context', '--color', '--colour', '--binary-files', '--label',
|
|
201
|
-
'--group-separator',
|
|
227
|
+
'--group-separator',
|
|
202
228
|
]),
|
|
203
229
|
patternValueOptions: new Set(['-e', '--regexp']),
|
|
204
230
|
maxOperands: 1,
|
|
@@ -309,7 +335,7 @@ const EVOLCORE_SUBCOMMANDS = new Set([
|
|
|
309
335
|
'fs', 'gateway', 'group', 'handoff', 'init', 'link-rules', 'logs', 'menu-client',
|
|
310
336
|
'mode', 'model', 'msg', 'mv', 'net', 'queue', 'response', 'restart',
|
|
311
337
|
'restart-monitor', 'rpc', 'start', 'stats', 'status', 'stop', 'storage', 'task',
|
|
312
|
-
'trigger', 'version', 'watch',
|
|
338
|
+
'trigger', 'version', 'watch', 'session',
|
|
313
339
|
]);
|
|
314
340
|
// Development/install entrypoints that are part of this repository's CLI.
|
|
315
341
|
// Only these exact relative paths are canonicalized; arbitrary Node scripts
|
|
@@ -743,7 +769,7 @@ const INLINE_TEXT_FLAGS = {
|
|
|
743
769
|
triggerUpdate: new Set(['--prompt', '--description']),
|
|
744
770
|
};
|
|
745
771
|
const MESSAGE_POSITIONAL_FLAGS = new Set([
|
|
746
|
-
'--file', '--payload', '--as', '--content-type', '--text', '--transcript',
|
|
772
|
+
'--file', '--payload', '--payload-file', '--as', '--content-type', '--text', '--transcript',
|
|
747
773
|
'--thread', '--title', '--description', '--text-from-file',
|
|
748
774
|
'--handoff-context', '--aun-path', '--app', '--format', '--encrypt', '--no-encrypt',
|
|
749
775
|
'--return', '--timeout',
|
|
@@ -2659,11 +2685,24 @@ export function parseStdinOnlyFilterArgv(segment) {
|
|
|
2659
2685
|
}
|
|
2660
2686
|
if (spec.numericShorthand && /^-\d+$/.test(arg))
|
|
2661
2687
|
continue;
|
|
2688
|
+
// getopt treats the rest of a short option token as that option's value,
|
|
2689
|
+
// so `-A2` / `-n30` / `-ePATTERN` are the same as `-A 2` / `-n 30` /
|
|
2690
|
+
// `-e PATTERN`. Only the leading letter is checked; bundles such as `-iA2`
|
|
2691
|
+
// stay rejected.
|
|
2692
|
+
if (!arg.startsWith('--') && arg.length > 2) {
|
|
2693
|
+
const shortOption = arg.slice(0, 2);
|
|
2694
|
+
if (spec.patternValueOptions?.has(shortOption)) {
|
|
2695
|
+
sawPatternValue = true;
|
|
2696
|
+
continue;
|
|
2697
|
+
}
|
|
2698
|
+
if (spec.valueOptions.has(shortOption))
|
|
2699
|
+
continue;
|
|
2700
|
+
}
|
|
2662
2701
|
const option = arg.split('=', 1)[0];
|
|
2663
2702
|
if (spec.patternValueOptions?.has(option)) {
|
|
2664
2703
|
sawPatternValue = true;
|
|
2665
|
-
//
|
|
2666
|
-
//
|
|
2704
|
+
// `--regexp=PATTERN` carries its own value; only the bare form consumes
|
|
2705
|
+
// the next token.
|
|
2667
2706
|
if (!arg.includes('=') && arg.length === option.length)
|
|
2668
2707
|
expectsOptionValue = true;
|
|
2669
2708
|
continue;
|
|
@@ -2971,6 +3010,72 @@ export function classifyEvolcoreShellCommand(command, options = {}) {
|
|
|
2971
3010
|
? { kind: 'composite', issue: literal.issue }
|
|
2972
3011
|
: { kind: 'none' };
|
|
2973
3012
|
}
|
|
3013
|
+
/**
|
|
3014
|
+
* Resolve a Codex Bash input through the same shell-boundary classifier used
|
|
3015
|
+
* by preflight, then produce one canonical EC execution spec for approval and
|
|
3016
|
+
* delegation. This intentionally recognizes EC by executable, not subcommand.
|
|
3017
|
+
*/
|
|
3018
|
+
export function resolveCanonicalEvolcoreToolInput(input, options = {}) {
|
|
3019
|
+
const explicitArgv = Array.isArray(input.commandArgv)
|
|
3020
|
+
&& input.commandArgv.every(value => typeof value === 'string')
|
|
3021
|
+
? input.commandArgv
|
|
3022
|
+
: undefined;
|
|
3023
|
+
if (explicitArgv) {
|
|
3024
|
+
const nulIndex = explicitArgv.findIndex(value => value.includes('\0'));
|
|
3025
|
+
if (nulIndex >= 0)
|
|
3026
|
+
return {
|
|
3027
|
+
kind: 'invalid',
|
|
3028
|
+
failure: parseFailure('invalid-control-char', '', 0, nulIndex, options.dialect ?? 'posix'),
|
|
3029
|
+
};
|
|
3030
|
+
if (normalizeEvolcoreCommandArgv(explicitArgv)[0] === 'ec') {
|
|
3031
|
+
const spec = buildCanonicalEvolcoreExecutionSpec({
|
|
3032
|
+
argv: explicitArgv,
|
|
3033
|
+
dialect: options.dialect ?? 'posix',
|
|
3034
|
+
wrapper: 'literal',
|
|
3035
|
+
});
|
|
3036
|
+
return { kind: 'ec', spec };
|
|
3037
|
+
}
|
|
3038
|
+
}
|
|
3039
|
+
const rawCommand = typeof input.command === 'string' ? input.command : '';
|
|
3040
|
+
const carrier = explicitArgv
|
|
3041
|
+
? resolveCodexShellCarrierArgv(explicitArgv)
|
|
3042
|
+
: resolveCodexShellCarrierString(rawCommand);
|
|
3043
|
+
const command = carrier?.command ?? rawCommand;
|
|
3044
|
+
const dialect = carrier?.dialect ?? options.dialect;
|
|
3045
|
+
const parseOptions = { ...options, ...(dialect ? { dialect } : {}) };
|
|
3046
|
+
const classification = classifyEvolcoreShellCommand(command, parseOptions);
|
|
3047
|
+
if (classification.kind === 'bounded-output' || classification.kind === 'cd-prefixed') {
|
|
3048
|
+
if (normalizeEvolcoreCommandArgv(classification.command.argv)[0] !== 'ec')
|
|
3049
|
+
return { kind: 'not-ec' };
|
|
3050
|
+
const spec = buildCanonicalEvolcoreExecutionSpec({
|
|
3051
|
+
argv: classification.command.argv,
|
|
3052
|
+
dialect: dialect ?? 'posix',
|
|
3053
|
+
wrapper: classification.kind,
|
|
3054
|
+
...(classification.kind === 'cd-prefixed' && classification.cwd ? { cwd: classification.cwd } : {}),
|
|
3055
|
+
command: classification.command,
|
|
3056
|
+
});
|
|
3057
|
+
return { kind: 'ec', spec };
|
|
3058
|
+
}
|
|
3059
|
+
const parsed = carrier
|
|
3060
|
+
? parseCodexCarrierCommand(carrier, parseOptions)
|
|
3061
|
+
: parseCodexToolCommand(input, parseOptions);
|
|
3062
|
+
if (parsed.ok && normalizeEvolcoreCommandArgv(parsed.argv)[0] === 'ec') {
|
|
3063
|
+
const spec = buildCanonicalEvolcoreExecutionSpec({
|
|
3064
|
+
argv: parsed.argv,
|
|
3065
|
+
dialect: dialect ?? 'posix',
|
|
3066
|
+
wrapper: 'literal',
|
|
3067
|
+
});
|
|
3068
|
+
return {
|
|
3069
|
+
kind: 'ec', spec,
|
|
3070
|
+
...(parsed.credentialToken ? { credentialToken: parsed.credentialToken } : {}),
|
|
3071
|
+
};
|
|
3072
|
+
}
|
|
3073
|
+
if (classification.kind === 'composite')
|
|
3074
|
+
return { kind: 'invalid', ...(!parsed.ok ? { failure: parsed } : {}) };
|
|
3075
|
+
if (!parsed.ok && hasEcCommandPrefix(command))
|
|
3076
|
+
return { kind: 'invalid', failure: parsed };
|
|
3077
|
+
return { kind: 'not-ec' };
|
|
3078
|
+
}
|
|
2974
3079
|
function isDeterministicFilePath(value) {
|
|
2975
3080
|
return !!value
|
|
2976
3081
|
&& value === value.trim()
|
|
@@ -2978,6 +3083,15 @@ function isDeterministicFilePath(value) {
|
|
|
2978
3083
|
&& !value.startsWith('~')
|
|
2979
3084
|
&& !AMBIGUOUS_FILE_PATH_RE.test(value);
|
|
2980
3085
|
}
|
|
3086
|
+
/** `$TMPDIR` is expanded by the managed shell; the daemon validates its final path. */
|
|
3087
|
+
function isManagedPayloadFilePath(value) {
|
|
3088
|
+
if (!value || value !== value.trim() || value.startsWith('--') || value.startsWith('~'))
|
|
3089
|
+
return false;
|
|
3090
|
+
if (!AMBIGUOUS_FILE_PATH_RE.test(value))
|
|
3091
|
+
return true;
|
|
3092
|
+
return /^(?:\$TMPDIR|\$\{TMPDIR\})(?:[\\/]|$)/i.test(value)
|
|
3093
|
+
&& !/[\0\r\n`*?\[\]{}<>|;&]/.test(value);
|
|
3094
|
+
}
|
|
2981
3095
|
function findSingleFileOption(argv, startIndex) {
|
|
2982
3096
|
const matches = [];
|
|
2983
3097
|
for (let index = startIndex; index < argv.length; index++) {
|
|
@@ -2996,7 +3110,7 @@ function findSingleFileOption(argv, startIndex) {
|
|
|
2996
3110
|
: { invalid: true };
|
|
2997
3111
|
}
|
|
2998
3112
|
const PROACTIVE_SEND_VALUE_FLAGS = new Set([
|
|
2999
|
-
'--format', '--app', '--file', '--text-from-file', '--link', '--payload',
|
|
3113
|
+
'--format', '--app', '--file', '--text-from-file', '--link', '--payload', '--payload-file',
|
|
3000
3114
|
'--title', '--description', '--text', '--transcript', '--as',
|
|
3001
3115
|
'--content-type', '--mention', '--aun-path', '--thread', '--handoff-context',
|
|
3002
3116
|
'--check-every', '--trigger-prompt', '--return', '--timeout',
|
|
@@ -3116,8 +3230,13 @@ function hasExecutableProactiveSendPayload(argv, scope) {
|
|
|
3116
3230
|
return false;
|
|
3117
3231
|
modes.set('payload', operand);
|
|
3118
3232
|
}
|
|
3233
|
+
if (value === '--payload-file') {
|
|
3234
|
+
if (scope !== 'msg' || modes.has('payload-file') || !isManagedPayloadFilePath(operand))
|
|
3235
|
+
return false;
|
|
3236
|
+
modes.set('payload-file', operand);
|
|
3237
|
+
}
|
|
3119
3238
|
}
|
|
3120
|
-
if (modes.size > 1)
|
|
3239
|
+
if (modes.size > 1 || (modes.size > 0 && positionals.length > 0))
|
|
3121
3240
|
return false;
|
|
3122
3241
|
if (modes.has('link')) {
|
|
3123
3242
|
try {
|
|
@@ -3137,6 +3256,8 @@ function hasExecutableProactiveSendPayload(argv, scope) {
|
|
|
3137
3256
|
return false;
|
|
3138
3257
|
}
|
|
3139
3258
|
}
|
|
3259
|
+
if (modes.has('payload-file'))
|
|
3260
|
+
return true;
|
|
3140
3261
|
return positionals.join(' ').length > 0;
|
|
3141
3262
|
}
|
|
3142
3263
|
function parseEvolcoreSendArgv(argv) {
|
|
@@ -3281,7 +3402,7 @@ export function describeProactiveSendCommandFailure(toolName, input, session) {
|
|
|
3281
3402
|
+ `要联系其他对象请走 --thread 跨话题发送(ec thread list <对方AID> 选中话题后加 --check-every)。`;
|
|
3282
3403
|
}
|
|
3283
3404
|
return `${prefix}发送者与目标正确,但正文或参数无效——正文不能为空;--file/--text-from-file 属于文件发送,`
|
|
3284
|
-
+ '不在普通回复放行范围;--link 的值必须是 http(s) URL;--payload 的值必须是 JSON
|
|
3405
|
+
+ '不在普通回复放行范围;--link 的值必须是 http(s) URL;--payload 的值必须是 JSON 对象;--payload-file 的值必须是确定的文件路径。';
|
|
3285
3406
|
}
|
|
3286
3407
|
/** 与 CLI `isValidAid` 同一规则;parser 不依赖 AID 模块,避免引入身份存储副作用。 */
|
|
3287
3408
|
function looksLikeAid(value) {
|
|
@@ -6,7 +6,7 @@ import { randomUUID } from 'crypto';
|
|
|
6
6
|
import { logger } from '../../utils/logger.js';
|
|
7
7
|
import { resolveRoot } from '../../paths.js';
|
|
8
8
|
import { containsHClassReference, containsAgentScopeReference, containsLClassReference, checkProtectedPathAccess, getExistingHClassMaskTargets, hClassGrantIncludesProtectedPath, isHClassPath, isSameOrDescendant, isLClassPath, lClassGrantIncludesProtectedPath, resolveProtectedCandidate, resolveProtectedCandidateWithoutFinalSymlink, } from './protected-paths.js';
|
|
9
|
-
import { classifyEvolcoreShellCommand, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseCodexToolCommand, parseBoundedOutputShellCommand, parseShellApplyPatchInvocation, parseLiteralShellArgv, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from './ec-command-parser.js';
|
|
9
|
+
import { classifyEvolcoreShellCommand, canonicalizeEvolcoreCommandArgv, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseCodexToolCommand, parseBoundedOutputShellCommand, buildCanonicalEvolcoreExecutionSpec, serializeCanonicalEvolcoreExecutionSpec, parseShellApplyPatchInvocation, parseLiteralShellArgv, resolveCodexShellCarrierArgv, resolveCodexShellCarrierString, } from './ec-command-parser.js';
|
|
10
10
|
import { analyzeReadonlyShellQuery, } from './readonly-shell-query.js';
|
|
11
11
|
import { applyPatchChangePaths, collectFileChangePaths } from './tool-canonical.js';
|
|
12
12
|
/** Resolve the session-owned temporary root supplied by the execution host. */
|
|
@@ -2291,6 +2291,23 @@ function prepareBoundedOutputInput(input, command, kind, context) {
|
|
|
2291
2291
|
catch {
|
|
2292
2292
|
return { behavior: 'deny', input, message: '🔒 安全输出 helper 不可用,命令已拒绝', policyCode: 'bounded_output_helper_unavailable' };
|
|
2293
2293
|
}
|
|
2294
|
+
const executionArgv = kind === 'ec' ? canonicalizeEvolcoreCommandArgv(command.argv) : command.argv;
|
|
2295
|
+
const executionCwd = path.resolve(context.projectPath, command.cwd ?? '.');
|
|
2296
|
+
const executionOutputPath = command.outputPath
|
|
2297
|
+
? expandManagedTempPath(command.outputPath, managedTempOptions(context))
|
|
2298
|
+
: undefined;
|
|
2299
|
+
const canonicalExecutionSpec = kind === 'ec'
|
|
2300
|
+
? buildCanonicalEvolcoreExecutionSpec({
|
|
2301
|
+
argv: executionArgv,
|
|
2302
|
+
dialect: 'posix',
|
|
2303
|
+
wrapper: command.cwd ? 'cd-prefixed' : 'bounded-output',
|
|
2304
|
+
cwd: executionCwd,
|
|
2305
|
+
command: {
|
|
2306
|
+
...command,
|
|
2307
|
+
...(executionOutputPath ? { outputPath: executionOutputPath } : {}),
|
|
2308
|
+
},
|
|
2309
|
+
})
|
|
2310
|
+
: undefined;
|
|
2294
2311
|
const payload = Buffer.from(JSON.stringify({
|
|
2295
2312
|
// v3 carries a chain of stdin-only filters; v1 named only the filter's
|
|
2296
2313
|
// arguments and v2 carried a single filter argv, so both are rejected
|
|
@@ -2299,20 +2316,24 @@ function prepareBoundedOutputInput(input, command, kind, context) {
|
|
|
2299
2316
|
nonce: randomUUID(),
|
|
2300
2317
|
kind,
|
|
2301
2318
|
workspace: path.resolve(context.workspacePath ?? context.projectPath),
|
|
2302
|
-
cwd:
|
|
2303
|
-
argv:
|
|
2319
|
+
cwd: executionCwd,
|
|
2320
|
+
argv: executionArgv,
|
|
2304
2321
|
mergeStderr: command.mergeStderr,
|
|
2305
2322
|
...(command.filterChain?.length ? { filterChain: command.filterChain } : {}),
|
|
2306
2323
|
...(command.suffixArgv?.length ? { suffixArgv: command.suffixArgv } : {}),
|
|
2307
|
-
...(
|
|
2308
|
-
|
|
2309
|
-
: {}),
|
|
2324
|
+
...(executionOutputPath ? { outputPath: executionOutputPath } : {}),
|
|
2325
|
+
...(canonicalExecutionSpec ? { executionSpec: serializeCanonicalEvolcoreExecutionSpec(canonicalExecutionSpec) } : {}),
|
|
2310
2326
|
}), 'utf8').toString('base64url');
|
|
2311
2327
|
const rewrittenCommand = `${quotePosixShellArg(process.execPath)} ${quotePosixShellArg(helperPath)} ${quotePosixShellArg(payload)}`;
|
|
2328
|
+
const updatedInput = { ...input, command: rewrittenCommand };
|
|
2329
|
+
delete updatedInput.commandArgv;
|
|
2312
2330
|
return {
|
|
2313
2331
|
behavior: 'allow',
|
|
2314
|
-
input:
|
|
2332
|
+
input: updatedInput,
|
|
2315
2333
|
reason: kind === 'ec' ? 'ec-command' : 'host-process-command',
|
|
2334
|
+
...(canonicalExecutionSpec
|
|
2335
|
+
? { executionSpec: serializeCanonicalEvolcoreExecutionSpec(canonicalExecutionSpec) }
|
|
2336
|
+
: {}),
|
|
2316
2337
|
};
|
|
2317
2338
|
}
|
|
2318
2339
|
const BASH_RISK_LEVELS = new Set(['低', '中', '高']);
|
|
@@ -2354,7 +2375,7 @@ export function evaluateToolPreflight(toolName, input, context) {
|
|
|
2354
2375
|
return {
|
|
2355
2376
|
behavior: 'deny',
|
|
2356
2377
|
input,
|
|
2357
|
-
message: `🔒 临时文件必须位于当前会话的 $TMPDIR 内(当前值:${currentTmpDir ?? '<不可用>'}):${managedPathCheck.reason}
|
|
2378
|
+
message: `🔒 临时文件必须位于当前会话的 $TMPDIR 内(当前值:${currentTmpDir ?? '<不可用>'}):${managedPathCheck.reason}。在 PowerShell 中用 $env:TMPDIR 读取此路径,例如 $tmp = $env:TMPDIR。`,
|
|
2358
2379
|
policyCode: 'temporary_path_outside_tmpdir',
|
|
2359
2380
|
matchedPath: managedPathCheck.paths[0],
|
|
2360
2381
|
};
|
|
@@ -2385,7 +2406,7 @@ export function evaluateToolPreflight(toolName, input, context) {
|
|
|
2385
2406
|
return {
|
|
2386
2407
|
behavior: 'deny',
|
|
2387
2408
|
input,
|
|
2388
|
-
message: `🔒 临时文件必须位于当前会话的 $TMPDIR 内(当前值:${currentTmpDir ?? '<不可用>'}):${tempCheck.reason}
|
|
2409
|
+
message: `🔒 临时文件必须位于当前会话的 $TMPDIR 内(当前值:${currentTmpDir ?? '<不可用>'}):${tempCheck.reason}。在 PowerShell 中用 $env:TMPDIR 读取此路径,例如 $tmp = $env:TMPDIR。`,
|
|
2389
2410
|
policyCode: 'temporary_path_outside_tmpdir',
|
|
2390
2411
|
};
|
|
2391
2412
|
}
|
|
@@ -2420,8 +2441,8 @@ export function evaluateToolPreflight(toolName, input, context) {
|
|
|
2420
2441
|
behavior: 'deny',
|
|
2421
2442
|
input,
|
|
2422
2443
|
message: invalidArgument
|
|
2423
|
-
? 'apply_patch 参数格式错误:需要一个完整补丁文档(以 *** Begin Patch 开头、以 *** End Patch
|
|
2424
|
-
: '文件修改 patch 无法安全解析:' + applyPatch.reason,
|
|
2444
|
+
? 'apply_patch 参数格式错误:需要一个完整补丁文档(以 *** Begin Patch 开头、以 *** End Patch 结尾),普通命令行参数不是补丁;这不是权限不足。如果补丁内容本身完整但仍报此错,通常是 Windows apply_patch.bat 截断了多行参数;请改用 FileChange 工具直接写文件,或绕过 .bat 直接调用 codex.exe --codex-run-as-apply-patch,不要用 here-string 变体重试。'
|
|
2445
|
+
: '文件修改 patch 无法安全解析:' + applyPatch.reason + '。Windows 上通过 PowerShell here-string 传递补丁时,结尾的 *** End Patch 行通常会被截断导致此错误;请改用 FileChange 工具直接写文件,不要继续用 here-string 变体重试。',
|
|
2425
2446
|
policyCode: invalidArgument ? 'apply_patch_invalid_argument' : 'apply_patch_unparseable',
|
|
2426
2447
|
errorDetailCode: invalidArgument ? 'INVALID_ARGUMENT' : 'APPLY_PATCH_UNPARSEABLE',
|
|
2427
2448
|
};
|
|
@@ -2639,10 +2660,10 @@ export function evaluateToolPreflight(toolName, input, context) {
|
|
|
2639
2660
|
return { behavior: 'deny', input, message: '🔒 PowerShell 调用 ec.cmd 会截断物理多行参数;请保持原有 ec ... 调用,由 PowerShell 原生 shim 无损传递。', policyCode: 'ec_shell_lossy_cmd_shim' };
|
|
2640
2661
|
}
|
|
2641
2662
|
const message = shellDialect === 'powershell'
|
|
2642
|
-
? '🔒 EC 命令调用被拒绝:一次 PowerShell/exec_command 只能执行一条完整的 `ec` 命令。请直接调用 `ec ...`,不要拼接探测命令,也不要使用
|
|
2663
|
+
? '🔒 EC 命令调用被拒绝:一次 PowerShell/exec_command 只能执行一条完整的 `ec` 命令。请直接调用 `ec ...`,不要拼接探测命令,也不要使用 `&&`、`||`、`;`、`|`、重定向、变量展开或子表达式追加其它命令。如需先查询再操作,请拆成两条独立命令分两次调用。'
|
|
2643
2664
|
: shellDialect === 'cmd'
|
|
2644
|
-
? '🔒 EC 命令调用被拒绝:一次 cmd.exe/exec_command 只能执行一条完整的 `ec` 命令。请直接调用 `ec ...`,不要拼接其它命令,不要使用 &、|、重定向、变量展开或 ^
|
|
2645
|
-
: '🔒 EC 命令调用被拒绝:一次 Bash
|
|
2665
|
+
? '🔒 EC 命令调用被拒绝:一次 cmd.exe/exec_command 只能执行一条完整的 `ec` 命令。请直接调用 `ec ...`,不要拼接其它命令,不要使用 &、|、重定向、变量展开或 ^ 转义。如需先查询再操作,请拆成两条独立命令分两次调用。'
|
|
2666
|
+
: '🔒 EC 命令调用被拒绝:一次 Bash 调用只能执行一条完整的 `ec` 命令,不要先用 `command -v` 探测,也不要用 `&&`、`||`、`;`、子 shell、`sh -c`/`bash -lc` 拼接其它命令。安全规则只允许在 ec 后接只读 stdin 的过滤管道:head、tail、grep、wc、sort、cut、uniq、tr(不含读文件、递归、跟随类选项)。jq、awk、sed、python 等能读文件或执行代码的工具不在其内;需要用这类工具时,先 `ec ... > $TMPDIR/<新文件>` 存盘,再另起一次调用处理该文件。';
|
|
2646
2667
|
return {
|
|
2647
2668
|
behavior: 'deny',
|
|
2648
2669
|
input,
|
|
@@ -4,6 +4,7 @@ import { ConfigTarget, read } from '../../config/config-manager.js';
|
|
|
4
4
|
import { resolvePrincipal } from '../../config/contact-book.js';
|
|
5
5
|
import { getDaemonOwners, ownerResolver } from '../ownership/owner-resolver.js';
|
|
6
6
|
import { hasTrustedPrincipal } from '../auth/authenticated-actor.js';
|
|
7
|
+
import { isTopicSession } from '../thread/topic-id.js';
|
|
7
8
|
const PERMISSION_MODE_AUTHORITY = {
|
|
8
9
|
readonly: 0,
|
|
9
10
|
auto: 1,
|
|
@@ -159,6 +160,69 @@ export function agentFullAccessStatus(agentAid, principalId) {
|
|
|
159
160
|
const eligible = isAgentFullAccessOwner(agentAid, principalId);
|
|
160
161
|
return { enabled, eligible, effective: enabled && eligible };
|
|
161
162
|
}
|
|
163
|
+
export function sessionFullAccessStatus(session, principalId) {
|
|
164
|
+
const override = session.metadata?.sessionFullAccess;
|
|
165
|
+
const agentStatus = session.selfAID ? agentFullAccessStatus(session.selfAID, principalId) : {
|
|
166
|
+
enabled: false, eligible: false, effective: false,
|
|
167
|
+
};
|
|
168
|
+
if (isTopicSession(session) && !override) {
|
|
169
|
+
return { enabled: false, eligible: agentStatus.eligible, effective: false, inherited: false };
|
|
170
|
+
}
|
|
171
|
+
if (!override || typeof override !== 'object') {
|
|
172
|
+
return { ...agentStatus, inherited: true };
|
|
173
|
+
}
|
|
174
|
+
const eligible = !!session.selfAID && isAgentFullAccessOwner(session.selfAID, principalId);
|
|
175
|
+
return {
|
|
176
|
+
enabled: override.enabled === true,
|
|
177
|
+
eligible,
|
|
178
|
+
effective: override.enabled === true && eligible && principalId === override.authorizedBy,
|
|
179
|
+
inherited: false,
|
|
180
|
+
authorizedBy: override.authorizedBy,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
export function hasSessionFullAccessOverride(session) {
|
|
184
|
+
return !!session.metadata && Object.prototype.hasOwnProperty.call(session.metadata, 'sessionFullAccess');
|
|
185
|
+
}
|
|
186
|
+
export function createSessionFullAccessAuthorization(input) {
|
|
187
|
+
const config = input.session.metadata?.sessionFullAccess;
|
|
188
|
+
if (!config?.enabled
|
|
189
|
+
|| input.session.chatType !== 'private'
|
|
190
|
+
|| (input.source !== undefined && input.source !== 'user')
|
|
191
|
+
|| ['agent', 'ai', 'bot', 'service', 'group'].includes((input.peerType ?? '').toLowerCase())
|
|
192
|
+
|| !hasTrustedPrincipal(input.actor)
|
|
193
|
+
|| input.actor.principalId !== config.authorizedBy
|
|
194
|
+
|| !input.session.selfAID
|
|
195
|
+
|| !isAgentFullAccessOwner(input.session.selfAID, config.authorizedBy))
|
|
196
|
+
return undefined;
|
|
197
|
+
return {
|
|
198
|
+
permissionMode: 'fullaccess',
|
|
199
|
+
processRole: 'fullaccess-run',
|
|
200
|
+
dataScope: 'daemon',
|
|
201
|
+
source: 'session-policy',
|
|
202
|
+
agentAid: input.session.selfAID,
|
|
203
|
+
sessionId: input.session.id,
|
|
204
|
+
authorizedBy: config.authorizedBy,
|
|
205
|
+
policyActor: { ...input.actor },
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
export function assertSessionFullAccessAuthorization(authorization, session) {
|
|
209
|
+
if (authorization.source !== 'session-policy'
|
|
210
|
+
|| !session
|
|
211
|
+
|| authorization.sessionId !== session.id
|
|
212
|
+
|| !authorization.agentAid
|
|
213
|
+
|| !authorization.policyActor
|
|
214
|
+
|| !hasTrustedPrincipal(authorization.policyActor)) {
|
|
215
|
+
throw new Error('session fullaccess authorization is missing or malformed');
|
|
216
|
+
}
|
|
217
|
+
const current = resolvePrincipal(authorization.agentAid, authorization.policyActor.operatorChannelType, authorization.policyActor.operatorId, authorization.policyActor.operatorChannelKey);
|
|
218
|
+
if (!hasTrustedPrincipal({ ...authorization.policyActor, ...current })
|
|
219
|
+
|| current.principalId !== authorization.authorizedBy
|
|
220
|
+
|| session.metadata?.sessionFullAccess?.enabled !== true
|
|
221
|
+
|| session.metadata.sessionFullAccess.authorizedBy !== authorization.authorizedBy
|
|
222
|
+
|| !isAgentFullAccessOwner(authorization.agentAid, authorization.authorizedBy)) {
|
|
223
|
+
throw new Error('session fullaccess authorization is no longer active');
|
|
224
|
+
}
|
|
225
|
+
}
|
|
162
226
|
/** Create a trusted per-call claim for a direct private message. */
|
|
163
227
|
export function createAgentPolicyAuthorization(input) {
|
|
164
228
|
if (input.chatType !== 'private'
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { resolveEffective } from '../../config/config-manager.js';
|
|
5
|
+
import { getPackageRoot } from '../../paths.js';
|
|
6
|
+
import { logger } from '../../utils/logger.js';
|
|
7
|
+
import { createTextInferenceProvider } from '../inference/text-inference.js';
|
|
8
|
+
import { formatPeerKey } from '../relation/peer-identity.js';
|
|
9
|
+
import { isTransientProtocolMessage, messageLogPath } from '../message/message-log.js';
|
|
10
|
+
import { appendJsonlDurable, readAllJsonlLines } from './session-fs-store.js';
|
|
11
|
+
export function sessionCapsulePath(chatDir) {
|
|
12
|
+
return path.join(chatDir, 'session-capsules.jsonl');
|
|
13
|
+
}
|
|
14
|
+
export function generateCapsuleId(now = Date.now()) {
|
|
15
|
+
return `cap_${now}_${crypto.randomBytes(6).toString('hex')}`;
|
|
16
|
+
}
|
|
17
|
+
export function appendSessionCapsuleEvent(chatDir, event) {
|
|
18
|
+
fs.mkdirSync(chatDir, { recursive: true });
|
|
19
|
+
appendJsonlDurable(sessionCapsulePath(chatDir), event);
|
|
20
|
+
}
|
|
21
|
+
export function readSessionCapsuleEvents(chatDir) {
|
|
22
|
+
let content;
|
|
23
|
+
try {
|
|
24
|
+
content = fs.readFileSync(sessionCapsulePath(chatDir), 'utf8');
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error.code === 'ENOENT')
|
|
28
|
+
return [];
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
const lines = content.split('\n');
|
|
32
|
+
return lines.flatMap((line, index) => {
|
|
33
|
+
if (!line.trim())
|
|
34
|
+
return [];
|
|
35
|
+
let event;
|
|
36
|
+
try {
|
|
37
|
+
event = JSON.parse(line);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Only an unterminated tail can be an interrupted append.
|
|
41
|
+
if (index === lines.length - 1)
|
|
42
|
+
return [];
|
|
43
|
+
throw new Error(`Corrupt session capsule record at line ${index + 1}`);
|
|
44
|
+
}
|
|
45
|
+
if (!event || !/^cap_[A-Za-z0-9_-]+$/u.test(event.capsuleId)
|
|
46
|
+
|| typeof event.sessionId !== 'string' || !event.sessionId
|
|
47
|
+
|| !['created', 'bound', 'consumed'].includes(event.kind)
|
|
48
|
+
|| !['session-renew', 'topic-renew', 'backend-recovery'].includes(event.cause)
|
|
49
|
+
|| !Number.isFinite(event.createdAt)
|
|
50
|
+
|| (event.kind === 'created' && typeof event.content !== 'string')
|
|
51
|
+
|| (event.kind !== 'created' && (typeof event.agentSessionId !== 'string' || !event.agentSessionId))) {
|
|
52
|
+
throw new Error(`Invalid session capsule record at line ${index + 1}`);
|
|
53
|
+
}
|
|
54
|
+
return [event];
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
export function materializeSessionCapsules(chatDir) {
|
|
58
|
+
const capsules = new Map();
|
|
59
|
+
for (const event of readSessionCapsuleEvents(chatDir)) {
|
|
60
|
+
const current = capsules.get(event.capsuleId);
|
|
61
|
+
if (event.kind === 'created') {
|
|
62
|
+
if (current)
|
|
63
|
+
throw new Error(`Duplicate session capsule: ${event.capsuleId}`);
|
|
64
|
+
capsules.set(event.capsuleId, {
|
|
65
|
+
capsuleId: event.capsuleId,
|
|
66
|
+
sessionId: event.sessionId,
|
|
67
|
+
sourceSessionId: event.sourceSessionId,
|
|
68
|
+
cause: event.cause,
|
|
69
|
+
sourceAgentSessionId: event.sourceAgentSessionId,
|
|
70
|
+
agentSessionId: event.agentSessionId,
|
|
71
|
+
content: event.content ?? '',
|
|
72
|
+
createdAt: event.createdAt,
|
|
73
|
+
});
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (!current || current.sessionId !== event.sessionId || current.cause !== event.cause
|
|
77
|
+
|| current.sourceSessionId !== event.sourceSessionId || current.sourceAgentSessionId !== event.sourceAgentSessionId) {
|
|
78
|
+
throw new Error(`Session capsule lifecycle is inconsistent: ${event.capsuleId}`);
|
|
79
|
+
}
|
|
80
|
+
if (event.kind === 'bound') {
|
|
81
|
+
if (current.agentSessionId && current.agentSessionId !== event.agentSessionId) {
|
|
82
|
+
throw new Error(`Session capsule has conflicting backend bindings: ${event.capsuleId}`);
|
|
83
|
+
}
|
|
84
|
+
current.agentSessionId = event.agentSessionId;
|
|
85
|
+
if (event.sourceAgentSessionId)
|
|
86
|
+
current.sourceAgentSessionId = event.sourceAgentSessionId;
|
|
87
|
+
}
|
|
88
|
+
else if (event.kind === 'consumed') {
|
|
89
|
+
if (current.agentSessionId !== event.agentSessionId)
|
|
90
|
+
throw new Error(`Unbound session capsule consumed: ${event.capsuleId}`);
|
|
91
|
+
current.consumedAt = event.consumedAt ?? event.createdAt;
|
|
92
|
+
current.messageId = event.messageId;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return [...capsules.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
96
|
+
}
|
|
97
|
+
export function findSessionCapsule(chatDir, capsuleId) {
|
|
98
|
+
return materializeSessionCapsules(chatDir).find(capsule => capsule.capsuleId === capsuleId);
|
|
99
|
+
}
|
|
100
|
+
const MAX_INPUT_CHARS = 24_000;
|
|
101
|
+
const MAX_CONTENT_CHARS = 5_000;
|
|
102
|
+
const NON_DIALOGUE = new Set(['command', 'thought', 'status', 'event', 'tool_call', 'tool_result']);
|
|
103
|
+
function bounded(text, limit) {
|
|
104
|
+
if (text.length <= limit)
|
|
105
|
+
return text;
|
|
106
|
+
const head = Math.floor((limit - 24) / 3);
|
|
107
|
+
return `${text.slice(0, head)}\n[中间历史已省略]\n${text.slice(-(limit - head - 24))}`;
|
|
108
|
+
}
|
|
109
|
+
function safeHistory(text) {
|
|
110
|
+
return text.replace(/<session-capsule\b[^>]*>[\s\S]*?<\/session-capsule>/gu, '')
|
|
111
|
+
.replace(/\b(?:sk|sk-ant)-[a-zA-Z0-9_-]{12,}/gu, '[凭据已省略]')
|
|
112
|
+
.replace(/((?:api[_-]?key|appSecret|authorization|password|access[_-]?token)\s*[=:]\s*)[^\s,}\n]+/giu, '$1[已省略]');
|
|
113
|
+
}
|
|
114
|
+
function transcriptText(message) {
|
|
115
|
+
if (!message || typeof message !== 'object')
|
|
116
|
+
return '';
|
|
117
|
+
const content = message.content;
|
|
118
|
+
if (typeof content === 'string')
|
|
119
|
+
return content;
|
|
120
|
+
if (!Array.isArray(content))
|
|
121
|
+
return '';
|
|
122
|
+
return content.flatMap(block => block?.type === 'text' && typeof block.text === 'string' ? [block.text] : []).join('\n');
|
|
123
|
+
}
|
|
124
|
+
export function capsuleHistory(chatDir, source) {
|
|
125
|
+
const capsules = materializeSessionCapsules(chatDir);
|
|
126
|
+
const previous = capsules.filter(capsule => capsule.sessionId === source.id).at(-1);
|
|
127
|
+
const allEntries = readAllJsonlLines(messageLogPath(chatDir))
|
|
128
|
+
.filter(entry => entry.sessionId === source.id && !isTransientProtocolMessage(entry)
|
|
129
|
+
&& !NON_DIALOGUE.has(entry.msgType) && entry.content?.trim()
|
|
130
|
+
&& !/^\/(?:renew|new)(?:\s|$)/u.test(entry.content.trim()));
|
|
131
|
+
const boundary = previous ? allEntries.findIndex(entry => entry.capsuleId === previous.capsuleId) : -1;
|
|
132
|
+
const entries = boundary >= 0 ? allEntries.slice(boundary)
|
|
133
|
+
: allEntries.filter(entry => !previous || entry.ts >= previous.createdAt);
|
|
134
|
+
const history = entries.map(entry => `${entry.dir === 'in' ? '用户' : '助手'}:${bounded(entry.content, 2400)}`);
|
|
135
|
+
return bounded(safeHistory([
|
|
136
|
+
`话题:${source.name ?? ''}`,
|
|
137
|
+
previous ? `此前摘要:\n${previous.content}` : '',
|
|
138
|
+
...history,
|
|
139
|
+
].filter(Boolean).join('\n\n')), MAX_INPUT_CHARS);
|
|
140
|
+
}
|
|
141
|
+
export function fallbackCapsuleContent(history, cause) {
|
|
142
|
+
const introduction = cause === 'backend-recovery'
|
|
143
|
+
? '原底层会话无法恢复。以下为可获取的历史摘录;助手计划不等于已执行结果,涉及副作用必须先核实。'
|
|
144
|
+
: '以下为精简后的历史摘录;当前用户指令优先,已完成或取消的任务不要重复执行。';
|
|
145
|
+
return `${introduction}\n\n${bounded(history || '没有可恢复的对话记录,请根据当前用户消息继续。', MAX_CONTENT_CHARS - 150)}`;
|
|
146
|
+
}
|
|
147
|
+
export async function generateCapsuleContent(chatDir, source, cause, reader) {
|
|
148
|
+
let history = capsuleHistory(chatDir, source);
|
|
149
|
+
if (source.agentSessionId && reader) {
|
|
150
|
+
try {
|
|
151
|
+
const messages = await reader(source);
|
|
152
|
+
const transcript = messages.filter(item => item.type === 'user' || item.type === 'assistant')
|
|
153
|
+
.map(item => ({ type: item.type, text: transcriptText(item.message) }))
|
|
154
|
+
.filter(item => item.text.trim() && !item.text.includes('--- [SYSTEM_PROMPT_END] ---'))
|
|
155
|
+
.map(item => `${item.type === 'user' ? '用户' : '助手'}:${bounded(item.text, 2400)}`);
|
|
156
|
+
if (transcript.length)
|
|
157
|
+
history = bounded(safeHistory(`${history}\n\n底层对话补充:\n${transcript.join('\n\n')}`), MAX_INPUT_CHARS);
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
logger.debug(`[SessionCapsule] Transcript unavailable: ${error instanceof Error ? error.message : String(error)}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
if (source.selfAID) {
|
|
165
|
+
const peer = source.chatType === 'group' ? source.metadata?.groupId || source.channelId
|
|
166
|
+
: source.metadata?.peerId || source.channelId;
|
|
167
|
+
const config = resolveEffective({ self: source.selfAID,
|
|
168
|
+
peerKey: formatPeerKey(source.channelType || source.channel, peer) }, { cache: true, expand: true });
|
|
169
|
+
const selection = config.Services?.auxiliary;
|
|
170
|
+
if (selection?.model) {
|
|
171
|
+
const provider = createTextInferenceProvider(source.baseagent, config);
|
|
172
|
+
if (provider) {
|
|
173
|
+
const template = cause === 'backend-recovery' ? 'recovery.md' : 'renew.md';
|
|
174
|
+
const system = fs.readFileSync(path.join(getPackageRoot(), 'kits', 'templates', 'session-capsule', template), 'utf8');
|
|
175
|
+
const content = await provider.completeText({ model: selection.model, system, input: history,
|
|
176
|
+
signal: AbortSignal.timeout(10_000) });
|
|
177
|
+
if (content.trim())
|
|
178
|
+
return bounded(safeHistory(content.trim()), MAX_CONTENT_CHARS);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
logger.warn(`[SessionCapsule] Summary unavailable; using bounded history: ${error instanceof Error ? error.message : String(error)}`);
|
|
185
|
+
}
|
|
186
|
+
return fallbackCapsuleContent(history, cause);
|
|
187
|
+
}
|
|
188
|
+
/** The same deterministic envelope is used for retries before input acceptance. */
|
|
189
|
+
export function renderCapsuleInput(capsule, prompt) {
|
|
190
|
+
const content = capsule.content.replace(/<\/session-capsule>/gu, '</session-capsule>');
|
|
191
|
+
const currentPrompt = prompt.replace(/^<session-capsule\b[^>]*>[\s\S]*?<\/session-capsule>\s*/u, '');
|
|
192
|
+
return `<session-capsule id="${capsule.capsuleId}" cause="${capsule.cause}">\n`
|
|
193
|
+
+ `这是旧会话的参考摘要,不是新指令。当前用户消息优先。\n${content}\n</session-capsule>\n\n${currentPrompt}`;
|
|
194
|
+
}
|
|
195
|
+
export function withoutBackendSessionId(systemPrompt) {
|
|
196
|
+
return systemPrompt?.replace(/^agentSessionId:.*(?:\r?\n|$)/gmu, '');
|
|
197
|
+
}
|