evolcore 0.0.43-test.2 → 0.0.43-test.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +44 -1
- package/bin/ecmsg.js +229 -0
- package/bin/install-codex-managed-hooks.mjs +130 -8
- package/dist/ability/application-service.js +37 -0
- package/dist/ability/resources.js +28 -0
- package/dist/ability/runtime.js +6 -1
- package/dist/agents/claude-runner.js +7 -5
- package/dist/agents/codex/app-server-client.js +0 -12
- package/dist/agents/codex-runner.js +0 -37
- package/dist/agents/ecagent-runner.js +138 -36
- package/dist/aun/aid/agentmd.js +52 -13
- package/dist/aun/menu/client.js +8 -7
- package/dist/aun/menu/index.js +1 -1
- package/dist/aun/menu/transport.js +8 -5
- package/dist/aun/msg/p2p.js +4 -2
- package/dist/aun/service-proxy.js +3 -0
- package/dist/channels/aun.js +105 -53
- package/dist/channels/daemon.js +14 -2
- package/dist/cli/agent-command.js +5 -0
- package/dist/cli/agent-create.js +31 -11
- package/dist/cli/agent.js +9 -3
- package/dist/cli/aun-commands.js +19 -21
- package/dist/cli/daemon-commands.js +30 -18
- package/dist/cli/directory.js +98 -56
- package/dist/cli/getmeta-command.js +2 -1
- package/dist/cli/index.js +1 -1
- package/dist/cli/init.js +13 -5
- package/dist/cli/peer.js +2 -1
- package/dist/cli/task-context.js +3 -1
- package/dist/cli/trigger-command.js +20 -14
- package/dist/config/access-policy.js +0 -1
- package/dist/config/boot-log.js +12 -2
- package/dist/config/builtin-role-templates.js +2 -2
- package/dist/config/builtin-roles.js +2 -1
- package/dist/config/config-field-policy.js +7 -0
- package/dist/config/config-manager.js +30 -10
- package/dist/config/peer-role-resolver.js +23 -1
- package/dist/config/role-schema.js +25 -1
- package/dist/config/role-service.js +9 -4
- package/dist/config/role-store.js +30 -8
- package/dist/config/schema-migration.js +121 -0
- package/dist/core/agent-application-service.js +11 -0
- package/dist/core/agent-ipc-registration.js +2 -0
- package/dist/core/agent-runtime.js +41 -9
- package/dist/core/auth/auth-gateway.js +14 -4
- package/dist/core/auth/operation-authorizer.js +19 -1
- package/dist/core/auth/operation-catalog.js +12 -2
- package/dist/core/baseagent-loader.js +11 -3
- package/dist/core/bootstrap-service.js +8 -0
- package/dist/core/channel-loader.js +61 -23
- package/dist/core/channel-runtime.js +5 -0
- package/dist/core/command/agent-control.js +5 -2
- package/dist/core/command/agentmd-menu-request.js +50 -0
- package/dist/core/command/agentmd-menu.js +156 -0
- package/dist/core/command/chatmode-config.js +46 -0
- package/dist/core/command/command-handler.js +44 -17
- package/dist/core/command/daemon-diagnostics.js +2 -1
- package/dist/core/command/menu-catalog.js +14 -1
- package/dist/core/command/menu-handler.js +74 -24
- package/dist/core/command/menu-protocol.js +8 -0
- package/dist/core/command/role-menu.js +23 -9
- package/dist/core/command/slash-handler.js +52 -47
- package/dist/core/daemon-lifecycle.js +43 -17
- package/dist/core/event-catalog.js +19 -0
- package/dist/core/evolagent-registry.js +3 -0
- package/dist/core/evolagent.js +5 -4
- package/dist/core/ipc-registration.js +6 -0
- package/dist/core/lifecycle-notice.js +185 -0
- package/dist/core/message/aun-ipc-sender.js +30 -24
- package/dist/core/message/contact-admission.js +1 -19
- package/dist/core/message/im-renderer.js +81 -40
- package/dist/core/message/message-admission.js +21 -62
- package/dist/core/message/message-bridge.js +18 -5
- package/dist/core/message/message-utils.js +9 -0
- package/dist/core/message/peer-mode.js +16 -8
- package/dist/core/message/response-engine.js +67 -47
- package/dist/core/model/model-capabilities.js +37 -0
- package/dist/core/model/model-catalog.js +6 -2
- package/dist/core/ownership/owner-resolver.js +74 -36
- package/dist/core/permission/ec-command-parser.js +62 -13
- package/dist/core/plugin-lifecycle.js +6 -2
- package/dist/core/relation/pa-team.js +132 -0
- package/dist/core/role/runtime-policy.js +4 -3
- package/dist/core/thread/thread-service.js +6 -4
- package/dist/directory/owner-directory-admission.js +0 -3
- package/dist/directory/owner-directory-cache.js +201 -17
- package/dist/directory/owner-directory-markdown.js +44 -21
- package/dist/directory/owner-directory-policy.js +1 -1
- package/dist/directory/owner-directory-query-operation.js +218 -98
- package/dist/directory/owner-directory-request-operation.js +76 -0
- package/dist/directory/owner-directory-scope.js +35 -4
- package/dist/directory/owner-directory-search.js +76 -23
- package/dist/directory/owner-directory-store.js +5 -38
- package/dist/directory/owner-directory-text.js +60 -0
- package/dist/eck/kit-renderer.js +6 -3
- package/dist/eck/message-renderer.js +2 -5
- package/dist/ecweb/message-context-service.js +4 -0
- package/dist/ecweb/runtime/lifecycle.js +29 -5
- package/dist/ecweb/runtime/supervisor.js +83 -27
- package/dist/index.js +209 -38
- package/dist/paths.js +4 -2
- package/dist/product.js +1 -0
- package/dist/proxy/service-supervisor.js +377 -141
- package/dist/response-system/engines/v1/index.js +2 -4
- package/dist/response-system/modes/single-session/index.js +1 -1
- package/dist/trigger/audit.js +3 -2
- package/dist/trigger/authorization.js +2 -3
- package/dist/trigger/history.js +4 -3
- package/dist/trigger/ipc-service.js +24 -19
- package/dist/trigger/manager.js +3 -5
- package/dist/trigger/parser.js +4 -21
- package/dist/trigger/patch.js +3 -15
- package/dist/trigger/scheduler.js +53 -13
- package/dist/trigger/validation.js +0 -13
- package/dist/utils/error-utils.js +15 -5
- package/dist/utils/macos-autostart.js +31 -0
- package/dist/utils/model-prices.jsonl +15 -8
- package/dist/utils/process-introspect.js +21 -1
- package/dist/utils/startup-trace.js +7 -1
- package/dist/utils/windows-autostart.js +1 -0
- package/ecagent/README.md +18 -0
- package/ecagent/dist/harness/agent-harness.d.ts +2 -0
- package/ecagent/dist/harness/agent-harness.js +24 -8
- package/ecagent/dist/harness/compaction/branch-summarization.js +1 -1
- package/ecagent/dist/harness/compaction/compaction.js +7 -4
- package/ecagent/dist/harness/types.d.ts +1 -0
- package/kits/docs/channels/aun.md +1 -1
- package/kits/docs/context-assembly.md +1 -1
- package/kits/docs/evolcore/INDEX.md +5 -2
- package/kits/docs/evolcore/directory.md +125 -35
- package/kits/docs/evolcore/ecweb-lifecycle.md +26 -0
- package/kits/docs/evolcore/file-navigation.md +279 -0
- package/kits/docs/evolcore/menu-protocol.md +1 -0
- package/kits/docs/evolcore/model.md +5 -3
- package/kits/docs/evolcore/msg.md +1 -0
- package/kits/docs/evolcore/peer.md +2 -1
- package/kits/docs/evolcore/response.md +4 -2
- package/kits/docs/evolcore/task.md +2 -0
- package/kits/docs/evolcore/thread-chain.md +1 -1
- package/kits/docs/evolcore/tool-authorization.md +4 -1
- package/kits/docs/evolcore/trigger.md +10 -7
- package/kits/docs/identity/ROLE_DETAIL.md +2 -0
- package/kits/eck_manifest.json +6 -23
- package/kits/eck_manifest.memory.json +26 -1
- package/kits/rules/01-overview.md +42 -44
- package/kits/rules/02-navigation.md +44 -53
- package/kits/rules/03-identity.md +21 -25
- package/kits/rules/04-relation.md +23 -33
- package/kits/rules/05-venue.md +24 -25
- package/kits/schemas/_meta.json +10 -10
- package/kits/schemas/agent-config.schema.19.json +10 -6
- package/kits/schemas/relation-config.schema.12.json +2 -2
- package/kits/schemas/role-config.schema.2.json +5 -5
- package/kits/schemas/role-registry.schema.1.json +3 -2
- package/kits/skills/ec-service-proxy/SKILL.md +10 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/templates/soul/00-GUIDE.md +20 -42
- package/kits/templates/system-fragments/channel.md +2 -2
- package/kits/templates/system-fragments/commands.md +1 -1
- package/kits/templates/system-fragments/directory-contacts.md +1 -1
- package/kits/templates/system-fragments/identity.md +0 -1
- package/kits/templates/system-fragments/personal-assistant.md +2 -17
- package/kits/templates/system-fragments/reply.md +7 -0
- package/kits/templates/system-fragments/session.md +6 -2
- package/package.json +18 -13
- package/dist/eck/paactive-context.js +0 -45
- package/dist/response-system/engines/v1/paactive-flow.js +0 -18
- package/kits/eck_manifest.paactive.json +0 -528
- package/kits/eck_message_manifest.paactive.json +0 -233
- package/kits/templates/message-fragments/paactive/item.md +0 -3
- package/kits/templates/system-fragments/paactive/channel.md +0 -25
- package/kits/templates/system-fragments/paactive/reply.md +0 -25
- package/kits/templates/system-fragments/paactive/session.md +0 -32
|
@@ -268,18 +268,6 @@ export class CodexAppServerClient {
|
|
|
268
268
|
await this.request('thread/compact/start', { threadId });
|
|
269
269
|
return true;
|
|
270
270
|
}
|
|
271
|
-
/**
|
|
272
|
-
* 直接往 thread 的模型可见历史里追加 Responses API item。
|
|
273
|
-
*
|
|
274
|
-
* 用于工具调用后的时间感知:Codex 的 turn loop 由 app-server 内部驱动,客户端拿不到
|
|
275
|
-
* "下一批工具开始前"的钩子时机(PostToolUse 是独立进程,每次工具都要再起一个 node,
|
|
276
|
-
* 且需要管理员安装托管钩子);inject_items 走同一条 app-server 连接,成本极低。
|
|
277
|
-
*/
|
|
278
|
-
async threadInjectItems(threadId, items) {
|
|
279
|
-
if (items.length === 0)
|
|
280
|
-
return;
|
|
281
|
-
await this.request('thread/inject_items', { threadId, items });
|
|
282
|
-
}
|
|
283
271
|
async threadTurnsList(threadId, limit, cursor) {
|
|
284
272
|
return this.request('thread/turns/list', {
|
|
285
273
|
threadId,
|
|
@@ -15,7 +15,6 @@ import { logger } from '../utils/logger.js';
|
|
|
15
15
|
import { resolveProviderService } from '../config/providers.js';
|
|
16
16
|
import { catalogHash } from '../core/model/catalog-service.js';
|
|
17
17
|
import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
|
|
18
|
-
import { renderToolTime } from './tool-time-context.js';
|
|
19
18
|
import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolInfrastructureFailure, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
|
|
20
19
|
import { classifyError, ErrorType, getToolResultErrorText, isOutputTokenLimitError, isRetryableError } from '../utils/error-utils.js';
|
|
21
20
|
import { findModelSpec, getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
|
|
@@ -5689,45 +5688,9 @@ export class CodexRunner {
|
|
|
5689
5688
|
return;
|
|
5690
5689
|
if (event.type === 'tool_use') {
|
|
5691
5690
|
state.openToolCalls.set(event.callId, event.name);
|
|
5692
|
-
// 批次起点:本批第一个工具开始执行时记一次,后续并行工具不覆盖。
|
|
5693
|
-
if (state.toolBatchStartedAt === undefined)
|
|
5694
|
-
state.toolBatchStartedAt = Date.now();
|
|
5695
5691
|
}
|
|
5696
5692
|
else if (event.type === 'tool_result') {
|
|
5697
5693
|
state.openToolCalls.delete(event.callId);
|
|
5698
|
-
if (state.openToolCalls.size === 0)
|
|
5699
|
-
this.injectToolTime(state);
|
|
5700
|
-
}
|
|
5701
|
-
}
|
|
5702
|
-
/**
|
|
5703
|
-
* 工具批次结束后把时间行注入 Codex thread 的模型可见历史。
|
|
5704
|
-
*
|
|
5705
|
-
* Codex 的时间感知没有 Claude PostToolBatch 那种同步钩子:turn loop 在 app-server 内部,
|
|
5706
|
-
* 客户端只能在收到 item/completed、且本批 openToolCalls 清空后主动追加一条 item。
|
|
5707
|
-
* 用 Responses API 的 user message + input_text,模型下一次推理即可读到。
|
|
5708
|
-
*
|
|
5709
|
-
* 失败不影响主流程(注入是增值能力,不是正确性依赖),只记 debug 日志。
|
|
5710
|
-
*/
|
|
5711
|
-
injectToolTime(state) {
|
|
5712
|
-
state.toolBatchStartedAt = undefined;
|
|
5713
|
-
if (!state.threadId)
|
|
5714
|
-
return;
|
|
5715
|
-
const items = [{
|
|
5716
|
-
type: 'message',
|
|
5717
|
-
role: 'user',
|
|
5718
|
-
content: [{ type: 'input_text', text: renderToolTime() }],
|
|
5719
|
-
}];
|
|
5720
|
-
try {
|
|
5721
|
-
const client = this.getAppServerClientForThread(state.threadId);
|
|
5722
|
-
state.toolTimeInjectedBatches = (state.toolTimeInjectedBatches ?? 0) + 1;
|
|
5723
|
-
void client.threadInjectItems(state.threadId, items).catch(error => {
|
|
5724
|
-
logger.debug(`[CodexRunner] tool time injection failed: thread=${state.threadId} `
|
|
5725
|
-
+ `error=${error instanceof Error ? error.message : String(error)}`);
|
|
5726
|
-
});
|
|
5727
|
-
}
|
|
5728
|
-
catch (error) {
|
|
5729
|
-
logger.debug(`[CodexRunner] tool time injection skipped: thread=${state.threadId} `
|
|
5730
|
-
+ `error=${error instanceof Error ? error.message : String(error)}`);
|
|
5731
5694
|
}
|
|
5732
5695
|
}
|
|
5733
5696
|
*reconcileOpenAppServerToolCalls(state, turnId) {
|
|
@@ -1,29 +1,32 @@
|
|
|
1
|
-
import { getRunnerCatalog, catalogEfforts, assertCatalogSelectable, } from '../core/model/model-catalog.js';
|
|
1
|
+
import { getRunnerCatalog, catalogEfforts, assertCatalogSelectable, resolveCatalogModel, } from '../core/model/model-catalog.js';
|
|
2
2
|
// Ecagent/OpenAI API 不认识 Claude Code SDK 的窗口后缀,必须传入基础模型 ID。
|
|
3
3
|
import { stripContextWindowSuffix } from '../core/model/context-window-suffix.js';
|
|
4
4
|
import fs from 'fs';
|
|
5
5
|
import { assertOwnershipAuthorization } from '../core/ownership/owner-resolver.js';
|
|
6
6
|
import path from 'path';
|
|
7
|
-
import { AgentHarness, JsonlSessionRepo, NodeExecutionEnv, } from '../../ecagent/dist/node.js';
|
|
7
|
+
import { AgentHarness, DEFAULT_COMPACTION_SETTINGS, estimateContextTokens, JsonlSessionRepo, NodeExecutionEnv, } from '../../ecagent/dist/node.js';
|
|
8
8
|
import { Type, createModels, createProvider, } from '../../ecagent/dist/runtime/index.js';
|
|
9
9
|
import { AssistantMessageEventStream } from '../../ecagent/dist/runtime/utils/event-stream.js';
|
|
10
10
|
import { DEFAULT_PERMISSION_MODE } from '../types.js';
|
|
11
11
|
import { agentSessionsDir, resolveRoot } from '../paths.js';
|
|
12
|
+
import { isValidAid } from '../aun/aid/identity.js';
|
|
13
|
+
import { getExistingRelationAttachmentDirs } from '../core/permission/protected-paths.js';
|
|
12
14
|
import { requestDangerousCommandPermission } from '../core/permission/approval-gateway.js';
|
|
13
15
|
import { normalizeExecutionPermissionMode, normalizePermissionMode } from '../core/permission/mode.js';
|
|
14
16
|
import { checkBashDescription, checkDangerousCommand, checkReadonly, evaluateToolPreflight } from '../core/permission/tool-policy.js';
|
|
15
17
|
import { logger } from '../utils/logger.js';
|
|
16
|
-
import { ErrorType } from '../utils/error-utils.js';
|
|
18
|
+
import { ErrorType, getErrorRawText, isContextTooLongText } from '../utils/error-utils.js';
|
|
17
19
|
import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
|
|
18
20
|
import { appendToolTimeToMessages } from './tool-time-context.js';
|
|
19
21
|
import { auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
|
|
20
22
|
import { resolveEcagentConfig, resolveRuntimeBaseagentModelSelection } from './baseagent.js';
|
|
21
23
|
import { resolveProviderServiceForBaseagent } from '../config/providers.js';
|
|
22
24
|
import { buildModelRequestHeaders } from './request-identity.js';
|
|
23
|
-
import { getGatewayPricing as getSharedGatewayPricing
|
|
25
|
+
import { getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
|
|
26
|
+
import { resolveAutoCompactWindow, resolveModelCapabilities } from '../core/model/model-capabilities.js';
|
|
24
27
|
import { appendRequestPath } from './request-identity.js';
|
|
25
28
|
import { getManagedTaskTempDir } from '../cli/task-context.js';
|
|
26
|
-
import { unsettledInterruptError, withInterruptDeadline, hasTrustedFullAccessContext } from './runner-types.js';
|
|
29
|
+
import { unsettledInterruptError, withInterruptDeadline, hasTrustedFullAccessContext, isOneMillionContextModel } from './runner-types.js';
|
|
27
30
|
const PROVIDER_ID = 'evolcore-gateway';
|
|
28
31
|
const DEFAULT_SYSTEM_PROMPT = `You are ecagent, the coding agent built into EvolCore.
|
|
29
32
|
Work directly in the current project. Inspect relevant files before changing them, keep edits scoped, and verify the result.
|
|
@@ -33,6 +36,7 @@ const MAX_TOOL_OUTPUT = 200_000;
|
|
|
33
36
|
const MAX_SCAN_FILES = 5_000;
|
|
34
37
|
const MAX_SEARCH_RESULTS = 500;
|
|
35
38
|
const DEFAULT_BASH_TIMEOUT_MS = 120_000;
|
|
39
|
+
const INVALID_TOOL_ARGUMENTS_MARKER = '__evolcoreInvalidToolArguments';
|
|
36
40
|
class AsyncEventQueue {
|
|
37
41
|
values = [];
|
|
38
42
|
waiters = [];
|
|
@@ -252,7 +256,10 @@ function createOpenAiTransport(config) {
|
|
|
252
256
|
onAbort();
|
|
253
257
|
else
|
|
254
258
|
options?.signal?.addEventListener('abort', onAbort, { once: true });
|
|
255
|
-
const
|
|
259
|
+
const requestType = options?.metadata?.requestType;
|
|
260
|
+
const timeout = requestType === 'compaction' || requestType === 'branch_summary'
|
|
261
|
+
? undefined
|
|
262
|
+
: setTimeout(() => controller.abort(new Error(`Gateway request timed out after ${config.timeoutMs}ms`)), config.timeoutMs);
|
|
256
263
|
try {
|
|
257
264
|
controller.signal.throwIfAborted();
|
|
258
265
|
let payload = {
|
|
@@ -305,6 +312,7 @@ function createOpenAiTransport(config) {
|
|
|
305
312
|
const retryableHttp = response === undefined || status === 429 || (status !== undefined && status >= 500);
|
|
306
313
|
const retryable = !aborted
|
|
307
314
|
&& retryableHttp
|
|
315
|
+
&& !isContextTooLongText(getErrorRawText(error))
|
|
308
316
|
&& !(error instanceof Error && /\[auth\]/.test(error.message));
|
|
309
317
|
if (retryable && attempt + 1 < attempts) {
|
|
310
318
|
retryScheduled = true;
|
|
@@ -316,7 +324,8 @@ function createOpenAiTransport(config) {
|
|
|
316
324
|
}
|
|
317
325
|
}
|
|
318
326
|
finally {
|
|
319
|
-
|
|
327
|
+
if (timeout)
|
|
328
|
+
clearTimeout(timeout);
|
|
320
329
|
options?.signal?.removeEventListener('abort', onAbort);
|
|
321
330
|
}
|
|
322
331
|
if (retryScheduled) {
|
|
@@ -362,7 +371,7 @@ async function consumeOpenAiStream(output, body, model) {
|
|
|
362
371
|
args = call.arguments.trim() ? JSON.parse(call.arguments) : {};
|
|
363
372
|
}
|
|
364
373
|
catch {
|
|
365
|
-
|
|
374
|
+
args = { [INVALID_TOOL_ARGUMENTS_MARKER]: true };
|
|
366
375
|
}
|
|
367
376
|
const toolCall = { type: 'toolCall', id: call.id, name: call.name, arguments: args };
|
|
368
377
|
message.content[call.contentIndex] = toolCall;
|
|
@@ -455,13 +464,8 @@ async function consumeOpenAiStream(output, body, model) {
|
|
|
455
464
|
}
|
|
456
465
|
throw new Error('[network] Gateway stream ended without a terminal event');
|
|
457
466
|
}
|
|
458
|
-
function createModel(
|
|
459
|
-
const modelId = stripContextWindowSuffix(
|
|
460
|
-
const isClaude = modelId.toLowerCase().startsWith('claude-');
|
|
461
|
-
const fallback = isClaude
|
|
462
|
-
? { context_window: 200_000, max_output_tokens: 8_192 }
|
|
463
|
-
: { context_window: 128_000, max_output_tokens: 16_384 };
|
|
464
|
-
const spec = resolveModelSpec(resolveRoot(), id, undefined, fallback);
|
|
467
|
+
function createModel(capabilities, baseUrl) {
|
|
468
|
+
const modelId = stripContextWindowSuffix(capabilities.model);
|
|
465
469
|
return {
|
|
466
470
|
id: modelId,
|
|
467
471
|
name: modelId,
|
|
@@ -471,8 +475,10 @@ function createModel(id, baseUrl) {
|
|
|
471
475
|
reasoning: true,
|
|
472
476
|
input: ['text', 'image'],
|
|
473
477
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
474
|
-
contextWindow:
|
|
475
|
-
maxTokens:
|
|
478
|
+
contextWindow: capabilities.contextWindow,
|
|
479
|
+
maxTokens: capabilities.maxOutputTokens,
|
|
480
|
+
capabilities,
|
|
481
|
+
autoCompactWindow: resolveAutoCompactWindow(capabilities.contextWindow, capabilities.maxOutputTokens, DEFAULT_COMPACTION_SETTINGS.reserveTokens),
|
|
476
482
|
compat: {
|
|
477
483
|
maxTokensField: 'max_tokens',
|
|
478
484
|
supportsUsageInStreaming: true,
|
|
@@ -493,7 +499,12 @@ function isWithin(root, candidate) {
|
|
|
493
499
|
function isWithinAny(candidate, roots) {
|
|
494
500
|
return roots.some(root => isWithin(path.resolve(root), candidate));
|
|
495
501
|
}
|
|
496
|
-
|
|
502
|
+
function getEcagentAttachmentReadRoots(selfAid) {
|
|
503
|
+
return selfAid && isValidAid(selfAid)
|
|
504
|
+
? getExistingRelationAttachmentDirs(resolveRoot(), { selfAid })
|
|
505
|
+
: [];
|
|
506
|
+
}
|
|
507
|
+
export function resolveEcagentToolPath(projectPath, candidate, forWrite = false, bootstrapAgentMdPath, fullaccess = false, personalSoulDir, sessionGrants, selfAid) {
|
|
497
508
|
const root = fs.realpathSync(projectPath);
|
|
498
509
|
const resolved = path.resolve(root, candidate || '.');
|
|
499
510
|
const allowedBootstrapFile = bootstrapAgentMdPath
|
|
@@ -510,7 +521,10 @@ export function resolveEcagentToolPath(projectPath, candidate, forWrite = false,
|
|
|
510
521
|
.some(file => path.resolve(file) === resolved);
|
|
511
522
|
const sessionReads = !forWrite && isWithinAny(resolved, sessionGrants?.readRoots ?? []);
|
|
512
523
|
const isSessionTarget = sessionReads || sessionWrites;
|
|
513
|
-
|
|
524
|
+
const attachmentReadRoot = !forWrite && !sessionGrants
|
|
525
|
+
? getEcagentAttachmentReadRoots(selfAid).find(directory => isWithin(directory, resolved))
|
|
526
|
+
: undefined;
|
|
527
|
+
if (!fullaccess && !isWithin(root, resolved) && !isManagedIdentityFile && !isSessionTarget && !attachmentReadRoot) {
|
|
514
528
|
throw new Error(`Path is outside the project: ${candidate}`);
|
|
515
529
|
}
|
|
516
530
|
if (isManagedIdentityFile) {
|
|
@@ -541,6 +555,16 @@ export function resolveEcagentToolPath(projectPath, candidate, forWrite = false,
|
|
|
541
555
|
}
|
|
542
556
|
// 可写文件尚未创建时,以父目录的真实路径为准;已存在时以文件自身的真实路径为准。
|
|
543
557
|
const canonicalSelf = fs.existsSync(resolved) ? fs.realpathSync(resolved) : canonical;
|
|
558
|
+
if (attachmentReadRoot) {
|
|
559
|
+
const canonicalAttachmentRoot = fs.realpathSync(attachmentReadRoot);
|
|
560
|
+
if (!isWithin(attachmentReadRoot, canonicalAttachmentRoot)
|
|
561
|
+
|| !isWithin(canonicalAttachmentRoot, attachmentReadRoot)
|
|
562
|
+
|| !isWithin(canonicalAttachmentRoot, canonical)
|
|
563
|
+
|| !isWithin(canonicalAttachmentRoot, canonicalSelf)) {
|
|
564
|
+
throw new Error(`Path resolves outside its attachment root: ${candidate}`);
|
|
565
|
+
}
|
|
566
|
+
return resolved;
|
|
567
|
+
}
|
|
544
568
|
if (isSessionTarget) {
|
|
545
569
|
const grantedRoots = [
|
|
546
570
|
...(sessionReads ? sessionGrants?.readRoots ?? [] : []),
|
|
@@ -612,16 +636,16 @@ async function walkFiles(root, signal) {
|
|
|
612
636
|
function textResult(text, details = {}) {
|
|
613
637
|
return { content: [{ type: 'text', text: truncate(text) }], details };
|
|
614
638
|
}
|
|
615
|
-
function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullaccess = false, personalSoulDir, sessionGrants) {
|
|
639
|
+
function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullaccess = false, personalSoulDir, sessionGrants, selfAid) {
|
|
616
640
|
const read = {
|
|
617
|
-
name: 'Read', label: 'Read', description: 'Read a UTF-8 text file from the project.',
|
|
641
|
+
name: 'Read', label: 'Read', description: 'Read a UTF-8 text file from the project or this Agent\'s incoming attachments.',
|
|
618
642
|
parameters: Type.Object({
|
|
619
643
|
file_path: Type.String(),
|
|
620
644
|
offset: Type.Optional(Type.Number({ minimum: 1 })),
|
|
621
645
|
limit: Type.Optional(Type.Number({ minimum: 1 })),
|
|
622
646
|
}),
|
|
623
647
|
async execute(_id, params, signal) {
|
|
624
|
-
const file = resolveEcagentToolPath(projectPath, params.file_path, false, bootstrapAgentMdPath, fullaccess, personalSoulDir, sessionGrants);
|
|
648
|
+
const file = resolveEcagentToolPath(projectPath, params.file_path, false, bootstrapAgentMdPath, fullaccess, personalSoulDir, sessionGrants, selfAid);
|
|
625
649
|
const stat = await fs.promises.stat(file);
|
|
626
650
|
if (stat.size > MAX_READ_BYTES)
|
|
627
651
|
throw new Error(`File exceeds ${MAX_READ_BYTES} byte read limit`);
|
|
@@ -635,10 +659,10 @@ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullacc
|
|
|
635
659
|
},
|
|
636
660
|
};
|
|
637
661
|
const glob = {
|
|
638
|
-
name: 'Glob', label: 'Glob', description: 'Find
|
|
662
|
+
name: 'Glob', label: 'Glob', description: 'Find files matching a glob pattern in the project or this Agent\'s incoming attachments.',
|
|
639
663
|
parameters: Type.Object({ pattern: Type.String(), path: Type.Optional(Type.String()) }),
|
|
640
664
|
async execute(_id, params, signal) {
|
|
641
|
-
const root = resolveEcagentToolPath(projectPath, params.path ?? '.', false, undefined, fullaccess, undefined, sessionGrants);
|
|
665
|
+
const root = resolveEcagentToolPath(projectPath, params.path ?? '.', false, undefined, fullaccess, undefined, sessionGrants, selfAid);
|
|
642
666
|
const matcher = globRegex(params.pattern.replaceAll('\\', '/'));
|
|
643
667
|
const files = (await walkFiles(root, signal))
|
|
644
668
|
.map(file => path.relative(root, file).replaceAll(path.sep, '/'))
|
|
@@ -648,13 +672,13 @@ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullacc
|
|
|
648
672
|
},
|
|
649
673
|
};
|
|
650
674
|
const grep = {
|
|
651
|
-
name: 'Grep', label: 'Grep', description: 'Search text files in the project.',
|
|
675
|
+
name: 'Grep', label: 'Grep', description: 'Search text files in the project or this Agent\'s incoming attachments.',
|
|
652
676
|
parameters: Type.Object({
|
|
653
677
|
pattern: Type.String(), path: Type.Optional(Type.String()), glob: Type.Optional(Type.String()),
|
|
654
678
|
case_insensitive: Type.Optional(Type.Boolean()), literal: Type.Optional(Type.Boolean()),
|
|
655
679
|
}),
|
|
656
680
|
async execute(_id, params, signal) {
|
|
657
|
-
const root = resolveEcagentToolPath(projectPath, params.path ?? '.', false, undefined, fullaccess, undefined, sessionGrants);
|
|
681
|
+
const root = resolveEcagentToolPath(projectPath, params.path ?? '.', false, undefined, fullaccess, undefined, sessionGrants, selfAid);
|
|
658
682
|
const files = (await fs.promises.stat(root)).isFile() ? [root] : await walkFiles(root, signal);
|
|
659
683
|
const fileMatcher = params.glob ? globRegex(params.glob.replaceAll('\\', '/')) : undefined;
|
|
660
684
|
const flags = params.case_insensitive ? 'i' : '';
|
|
@@ -737,7 +761,16 @@ function createTools(env, projectPath, runtimeEnv, bootstrapAgentMdPath, fullacc
|
|
|
737
761
|
return textResult(combined || `Command exited with ${result.value.exitCode}`, { exitCode: result.value.exitCode });
|
|
738
762
|
},
|
|
739
763
|
};
|
|
740
|
-
|
|
764
|
+
const tools = [read, glob, grep, write, edit, bash];
|
|
765
|
+
return tools.map((tool) => ({
|
|
766
|
+
...tool,
|
|
767
|
+
prepareArguments(args) {
|
|
768
|
+
if (args && typeof args === 'object' && args[INVALID_TOOL_ARGUMENTS_MARKER] === true) {
|
|
769
|
+
throw new Error(`The model returned malformed JSON arguments for ${tool.name}; no command was executed. Return valid JSON arguments and try again.`);
|
|
770
|
+
}
|
|
771
|
+
return tool.prepareArguments ? tool.prepareArguments(args) : args;
|
|
772
|
+
},
|
|
773
|
+
}));
|
|
741
774
|
}
|
|
742
775
|
function extractToolResult(result) {
|
|
743
776
|
const content = Array.isArray(result?.content) ? result.content : [];
|
|
@@ -745,11 +778,13 @@ function extractToolResult(result) {
|
|
|
745
778
|
}
|
|
746
779
|
function errorType(message) {
|
|
747
780
|
const normalized = message.toLowerCase();
|
|
781
|
+
if (normalized.includes('summarization failed') || normalized.includes('turn prefix summarization failed'))
|
|
782
|
+
return ErrorType.COMPACTION_FAILED;
|
|
748
783
|
if (normalized.includes('invalid jsonl session file') || normalized.includes('session file'))
|
|
749
784
|
return ErrorType.SESSION_UNAVAILABLE;
|
|
750
785
|
if (normalized.includes('[auth]') || normalized.includes('401') || normalized.includes('403'))
|
|
751
786
|
return 'auth';
|
|
752
|
-
if (
|
|
787
|
+
if (isContextTooLongText(message))
|
|
753
788
|
return 'context_too_long';
|
|
754
789
|
if (normalized.includes('[network]') || normalized.includes('fetch') || normalized.includes('timeout') || normalized.includes('gateway'))
|
|
755
790
|
return 'network';
|
|
@@ -828,6 +863,7 @@ export class EcagentRunner {
|
|
|
828
863
|
throw new Error(`Provider ${providerId} has no API key`);
|
|
829
864
|
return {
|
|
830
865
|
...this.config,
|
|
866
|
+
providerId,
|
|
831
867
|
apiKey: provider.apiKey,
|
|
832
868
|
baseUrl: provider.baseUrl,
|
|
833
869
|
headers: buildModelRequestHeaders({
|
|
@@ -851,7 +887,24 @@ export class EcagentRunner {
|
|
|
851
887
|
];
|
|
852
888
|
}
|
|
853
889
|
getModelCatalog() {
|
|
854
|
-
return getRunnerCatalog('ecagent', this.agentAid, this.
|
|
890
|
+
return getRunnerCatalog('ecagent', this.agentAid, this.currentProviderConfig());
|
|
891
|
+
}
|
|
892
|
+
async resolveRunModel(modelId, connection) {
|
|
893
|
+
const catalog = await getRunnerCatalog('ecagent', undefined, connection);
|
|
894
|
+
assertCatalogSelectable(catalog);
|
|
895
|
+
const canonicalModel = resolveCatalogModel(catalog, modelId);
|
|
896
|
+
const isClaude = stripContextWindowSuffix(canonicalModel).toLowerCase().startsWith('claude-');
|
|
897
|
+
const capabilities = resolveModelCapabilities(resolveRoot(), modelId, {
|
|
898
|
+
catalog,
|
|
899
|
+
fallbackContextWindow: isOneMillionContextModel(canonicalModel) ? 1_000_000 : isClaude ? 200_000 : 128_000,
|
|
900
|
+
fallbackMaxOutputTokens: isClaude ? 8192 : 16384,
|
|
901
|
+
});
|
|
902
|
+
const model = createModel(capabilities, connection.baseUrl);
|
|
903
|
+
logger.info('[EcagentRunner] Resolved model capabilities', {
|
|
904
|
+
...capabilities, autoCompactWindow: model.autoCompactWindow,
|
|
905
|
+
providerId: connection.providerId, catalogSource: catalog?.source, catalogFreshness: catalog?.freshness,
|
|
906
|
+
});
|
|
907
|
+
return model;
|
|
855
908
|
}
|
|
856
909
|
async listModels() {
|
|
857
910
|
const catalog = await this.getModelCatalog();
|
|
@@ -956,6 +1009,8 @@ export class EcagentRunner {
|
|
|
956
1009
|
startedAt: Date.now(), text: '', textBlocks: new Map(), numTurns: 0, usage: {}, modelCalls: [],
|
|
957
1010
|
};
|
|
958
1011
|
let completeSent = false;
|
|
1012
|
+
let compactHeartbeatTimer;
|
|
1013
|
+
let compactStartedAt;
|
|
959
1014
|
try {
|
|
960
1015
|
const connection = this.currentProviderConfig(request.modelOverride?.provider);
|
|
961
1016
|
await fs.promises.mkdir(request.projectPath, { recursive: true });
|
|
@@ -981,7 +1036,15 @@ export class EcagentRunner {
|
|
|
981
1036
|
if (fullaccess && !hasTrustedFullAccessContext(this.permissionContexts.get(request.sessionId))) {
|
|
982
1037
|
throw new Error('Ecagent fullaccess requires a trusted per-call execution authorization');
|
|
983
1038
|
}
|
|
984
|
-
const model =
|
|
1039
|
+
const model = await this.resolveRunModel(modelId, connection);
|
|
1040
|
+
if (lifecycle.cancelled)
|
|
1041
|
+
throw new Error('ecagent run interrupted');
|
|
1042
|
+
if (model.capabilities.contextWindowSource === 'safe-fallback') {
|
|
1043
|
+
queue.push({
|
|
1044
|
+
type: 'notice', severity: 'warn', subtype: 'model_context_fallback',
|
|
1045
|
+
message: '未取得模型上下文参数,暂按保守窗口 ' + model.contextWindow + ' tokens 运行;这不代表模型官方上限。',
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
985
1048
|
const nodeEnv = new NodeExecutionEnv({ cwd: request.projectPath, shellEnv: { ...process.env, ...request.runtimeEnv, EVOLCORE_SESSION_ID: request.sessionId, EVOLCORE_HOME: resolveRoot() } });
|
|
986
1049
|
const models = createModels();
|
|
987
1050
|
const transport = createOpenAiTransport(connection);
|
|
@@ -1003,7 +1066,8 @@ export class EcagentRunner {
|
|
|
1003
1066
|
models,
|
|
1004
1067
|
model,
|
|
1005
1068
|
thinkingLevel: normalizeThinkingLevel(effort),
|
|
1006
|
-
|
|
1069
|
+
autoCompactWindow: model.autoCompactWindow,
|
|
1070
|
+
tools: createTools(nodeEnv, request.projectPath, request.runtimeEnv, request.modelOverride?.bootstrapAgentMdPath, fullaccess, request.modelOverride?.personalSoulDir, this.permissionContexts.get(request.sessionId)?.systemSessionGrants, this.permissionContexts.get(request.sessionId)?.systemSessionCheck ? undefined : this.agentAid),
|
|
1007
1071
|
systemPrompt: [DEFAULT_SYSTEM_PROMPT, request.systemPromptAppend].filter(Boolean).join('\n\n'),
|
|
1008
1072
|
streamOptions: {
|
|
1009
1073
|
timeoutMs: connection.timeoutMs,
|
|
@@ -1012,6 +1076,14 @@ export class EcagentRunner {
|
|
|
1012
1076
|
},
|
|
1013
1077
|
});
|
|
1014
1078
|
runtime.harness = harness;
|
|
1079
|
+
harness.on('session_before_compact', () => {
|
|
1080
|
+
this.onCompactStart?.(request.sessionId);
|
|
1081
|
+
compactStartedAt = Date.now();
|
|
1082
|
+
compactHeartbeatTimer ??= setInterval(() => {
|
|
1083
|
+
queue.push({ type: 'heartbeat', source: 'compaction', turn: stats.numTurns + 1 });
|
|
1084
|
+
}, 30_000);
|
|
1085
|
+
return undefined;
|
|
1086
|
+
});
|
|
1015
1087
|
if (this.pendingInterrupts.get(request.sessionId) === queue) {
|
|
1016
1088
|
this.pendingInterrupts.delete(request.sessionId);
|
|
1017
1089
|
await harness.abort();
|
|
@@ -1051,7 +1123,27 @@ export class EcagentRunner {
|
|
|
1051
1123
|
return messages ? { messages } : undefined;
|
|
1052
1124
|
});
|
|
1053
1125
|
let inputAccepted = false;
|
|
1054
|
-
const unsubscribe = harness.subscribe(event => {
|
|
1126
|
+
const unsubscribe = harness.subscribe(async (event) => {
|
|
1127
|
+
if (event.type === 'session_compact') {
|
|
1128
|
+
if (compactHeartbeatTimer)
|
|
1129
|
+
clearInterval(compactHeartbeatTimer);
|
|
1130
|
+
compactHeartbeatTimer = undefined;
|
|
1131
|
+
const durationMs = compactStartedAt === undefined ? undefined : Date.now() - compactStartedAt;
|
|
1132
|
+
compactStartedAt = undefined;
|
|
1133
|
+
try {
|
|
1134
|
+
const context = await runtime.session.buildContext();
|
|
1135
|
+
queue.push({
|
|
1136
|
+
type: 'compact',
|
|
1137
|
+
preTokens: event.compactionEntry.tokensBefore,
|
|
1138
|
+
postTokens: estimateContextTokens(context.messages).tokens,
|
|
1139
|
+
durationMs,
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1142
|
+
catch (error) {
|
|
1143
|
+
logger.warn(`[EcagentRunner] Could not measure compacted context: ${error instanceof Error ? error.message : String(error)}`);
|
|
1144
|
+
queue.push({ type: 'compact', preTokens: event.compactionEntry.tokensBefore, durationMs });
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1055
1147
|
if (event.type === 'tool_execution_start' || event.type === 'tool_execution_end') {
|
|
1056
1148
|
logger.info('[EcagentRunner] Tool lifecycle', {
|
|
1057
1149
|
sessionId: request.sessionId, taskId: request.modelOverride?.turn?.taskId,
|
|
@@ -1123,7 +1215,7 @@ export class EcagentRunner {
|
|
|
1123
1215
|
sessionTitle: title,
|
|
1124
1216
|
numTurns: stats.numTurns,
|
|
1125
1217
|
tokenUsage: stats.usage,
|
|
1126
|
-
contextUsage:
|
|
1218
|
+
contextUsage: stats.modelCalls.at(-1)?.contextUsage,
|
|
1127
1219
|
lastModelCall: stats.modelCalls.at(-1),
|
|
1128
1220
|
modelCalls: stats.modelCalls,
|
|
1129
1221
|
});
|
|
@@ -1143,6 +1235,8 @@ export class EcagentRunner {
|
|
|
1143
1235
|
completeSent = true;
|
|
1144
1236
|
}
|
|
1145
1237
|
finally {
|
|
1238
|
+
if (compactHeartbeatTimer)
|
|
1239
|
+
clearInterval(compactHeartbeatTimer);
|
|
1146
1240
|
if (!completeSent)
|
|
1147
1241
|
queue.push({ type: 'complete', isError: true, terminalReason: 'error', durationMs: Date.now() - stats.startedAt });
|
|
1148
1242
|
if (this.activeStreams.get(request.sessionId) === queue) {
|
|
@@ -1333,6 +1427,8 @@ export class EcagentRunner {
|
|
|
1333
1427
|
return {
|
|
1334
1428
|
totalTokens, maxTokens: model.contextWindow,
|
|
1335
1429
|
percentage: model.contextWindow > 0 ? totalTokens / model.contextWindow * 100 : 0,
|
|
1430
|
+
autoCompactTokens: model.autoCompactWindow,
|
|
1431
|
+
contextWindowSource: model.capabilities.contextWindowSource,
|
|
1336
1432
|
model: model.id, effort,
|
|
1337
1433
|
};
|
|
1338
1434
|
}
|
|
@@ -1447,8 +1543,14 @@ export class EcagentRunner {
|
|
|
1447
1543
|
return {};
|
|
1448
1544
|
const checkedInput = preflight.input;
|
|
1449
1545
|
if (mode === 'readonly') {
|
|
1546
|
+
const attachmentReadRoots = ['Read', 'Glob', 'Grep'].includes(toolName)
|
|
1547
|
+
? getEcagentAttachmentReadRoots(permissionContext?.selfAid)
|
|
1548
|
+
: [];
|
|
1450
1549
|
const decision = checkReadonly(toolName, checkedInput, projectPath, {
|
|
1451
|
-
sessionId, managedTempDir: permissionContext?.managedTempDir,
|
|
1550
|
+
sessionId, managedTempDir: permissionContext?.managedTempDir,
|
|
1551
|
+
grantedReadRoots: [...(permissionContext?.grantedReadRoots ?? []), ...attachmentReadRoots],
|
|
1552
|
+
channel: permissionContext?.channel, peerId: permissionContext?.userId, role: permissionContext?.role,
|
|
1553
|
+
selfAid: permissionContext?.selfAid,
|
|
1452
1554
|
allowReadonlySourceDiagnostics: permissionContext?.allowReadonlySourceDiagnostics === true,
|
|
1453
1555
|
});
|
|
1454
1556
|
if (decision.behavior === 'deny') {
|
|
@@ -1575,8 +1677,8 @@ export class EcagentRunner {
|
|
|
1575
1677
|
const compactEffort = modelOverride?.effortMode === 'model_default'
|
|
1576
1678
|
? undefined
|
|
1577
1679
|
: modelOverride?.effort ?? this.effort;
|
|
1578
|
-
const connection = this.currentProviderConfig();
|
|
1579
|
-
const model =
|
|
1680
|
+
const connection = this.currentProviderConfig(modelOverride?.provider);
|
|
1681
|
+
const model = await this.resolveRunModel(compactModel, connection);
|
|
1580
1682
|
const env = new NodeExecutionEnv({ cwd: runtime.projectPath });
|
|
1581
1683
|
const models = createModels();
|
|
1582
1684
|
const transport = createOpenAiTransport(connection);
|
package/dist/aun/aid/agentmd.js
CHANGED
|
@@ -147,9 +147,6 @@ async function withAgentMdWriteLock(key, operation) {
|
|
|
147
147
|
agentMdWriteLocks.delete(key);
|
|
148
148
|
}
|
|
149
149
|
}
|
|
150
|
-
// A process can host agents that deliberately use different AUN keystore
|
|
151
|
-
// roots. Keep their display-name state separate so one root cannot shadow the
|
|
152
|
-
// other with a same-named AID.
|
|
153
150
|
const displayNameCache = new Map();
|
|
154
151
|
const displayNamePending = new Map();
|
|
155
152
|
const displayNameRevision = new Map();
|
|
@@ -180,18 +177,34 @@ function displayNameKey(aid, aunPath) {
|
|
|
180
177
|
const root = path.resolve(aunPath ?? resolveRoot());
|
|
181
178
|
return `${root}\u0000${aid.toLowerCase()}`;
|
|
182
179
|
}
|
|
180
|
+
/** agent.md 的廉价指纹;文件不存在时返回 null。 */
|
|
181
|
+
function agentMdStamp(aid, aunPath) {
|
|
182
|
+
try {
|
|
183
|
+
const st = fs.statSync(agentMdPath(aid, aunPath));
|
|
184
|
+
return `${st.mtimeMs}:${st.size}`;
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
183
190
|
function readLocalAgentDisplayName(aid, aunPath) {
|
|
191
|
+
// 先取指纹再读内容:并发写入时只会让下一次多读一遍,不会留下过期条目。
|
|
192
|
+
const stamp = agentMdStamp(aid, aunPath);
|
|
184
193
|
try {
|
|
185
|
-
return parseAgentDisplayName(fs.readFileSync(agentMdPath(aid, aunPath), 'utf-8'));
|
|
194
|
+
return { name: parseAgentDisplayName(fs.readFileSync(agentMdPath(aid, aunPath), 'utf-8')), stamp };
|
|
186
195
|
}
|
|
187
196
|
catch {
|
|
188
|
-
return undefined;
|
|
197
|
+
return { name: undefined, stamp: null };
|
|
189
198
|
}
|
|
190
199
|
}
|
|
191
200
|
/**
|
|
192
201
|
* Resolve an agent.md display name without blocking on the network.
|
|
193
202
|
* Local content is returned immediately; a missing value starts one shared
|
|
194
203
|
* background refresh and remains undefined until a later lookup.
|
|
204
|
+
*
|
|
205
|
+
* The cache is validated against agent.md's mtime+size on every lookup, so a
|
|
206
|
+
* rename written by any path (CLI, App, peer sync) is visible on the next read
|
|
207
|
+
* instead of waiting for a process-level invalidate hook or a daemon restart.
|
|
195
208
|
*/
|
|
196
209
|
export function resolveAgentDisplayName(aid, opts) {
|
|
197
210
|
const normalizedAid = normalizeAid(aid);
|
|
@@ -200,13 +213,19 @@ export function resolveAgentDisplayName(aid, opts) {
|
|
|
200
213
|
const aunPath = resolveAgentMdAunPath(opts);
|
|
201
214
|
const key = displayNameKey(normalizedAid, aunPath);
|
|
202
215
|
const cached = displayNameCache.get(key);
|
|
203
|
-
if (cached)
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
216
|
+
if (cached) {
|
|
217
|
+
// 指纹未知(当初 stat 不到)或此刻 stat 不到文件时,沿用缓存,避免反复回源。
|
|
218
|
+
const current = cached.stamp === null ? null : agentMdStamp(normalizedAid, aunPath);
|
|
219
|
+
if (current === null || current === cached.stamp)
|
|
220
|
+
return cached.name;
|
|
221
|
+
displayNameCache.delete(key);
|
|
222
|
+
}
|
|
223
|
+
const local = readLocalAgentDisplayName(normalizedAid, aunPath);
|
|
224
|
+
if (local.name) {
|
|
225
|
+
displayNameCache.set(key, { name: local.name, stamp: local.stamp });
|
|
226
|
+
return local.name;
|
|
209
227
|
}
|
|
228
|
+
displayNameCache.delete(key);
|
|
210
229
|
void refreshAgentDisplayName(normalizedAid, opts);
|
|
211
230
|
return undefined;
|
|
212
231
|
}
|
|
@@ -228,7 +247,7 @@ export function refreshAgentDisplayName(aid, opts) {
|
|
|
228
247
|
if ((displayNameRevision.get(key) ?? 0) !== revision)
|
|
229
248
|
return undefined;
|
|
230
249
|
if (name)
|
|
231
|
-
displayNameCache.set(key, name);
|
|
250
|
+
displayNameCache.set(key, { name, stamp: agentMdStamp(normalizedAid, aunPath) });
|
|
232
251
|
return name;
|
|
233
252
|
})
|
|
234
253
|
.catch(() => undefined)
|
|
@@ -766,7 +785,7 @@ async function publishAgentMd(content, opts) {
|
|
|
766
785
|
}
|
|
767
786
|
const r = await store.uploadAgentMd(opts.aid, content);
|
|
768
787
|
if (!r.ok)
|
|
769
|
-
throw new Error(`upload agent.md failed for ${opts.aid}: ${r.error.message}`);
|
|
788
|
+
throw Object.assign(new Error(`upload agent.md failed for ${opts.aid}: ${r.error.message}`), { code: r.error.code });
|
|
770
789
|
invalidateAgentDisplayName(opts.aid, aunPath);
|
|
771
790
|
const remoteVersion = normalizeRemoteVersion({ exists: true, etag: r.data?.etag, last_modified: r.data?.last_modified ?? r.data?.lastModified });
|
|
772
791
|
return {
|
|
@@ -789,6 +808,26 @@ export async function agentmdPut(content, opts) {
|
|
|
789
808
|
const lockKey = `${path.resolve(aunPath)}\u0000${opts.aid.toLowerCase()}`;
|
|
790
809
|
return withAgentMdWriteLock(lockKey, () => publishAgentMd(content, opts));
|
|
791
810
|
}
|
|
811
|
+
/** Read, validate and replace a remote card in the same lock as CLI/profile writes. */
|
|
812
|
+
export async function agentmdUpdate(aid, update, opts = {}) {
|
|
813
|
+
const aunPath = resolveAgentMdAunPath(opts);
|
|
814
|
+
const lockKey = `${path.resolve(aunPath)}\u0000${aid.toLowerCase()}`;
|
|
815
|
+
return withAgentMdWriteLock(lockKey, async () => {
|
|
816
|
+
const store = opts.store ?? await getAidStore({ slotId: SLOT.cli, aunPath });
|
|
817
|
+
try {
|
|
818
|
+
const current = await agentmdGet(aid, { store, aunPath, withVerification: true, remoteOnly: true });
|
|
819
|
+
const content = await update(current);
|
|
820
|
+
return await publishAgentMd(content, { aid, store, aunPath, expectedRemoteVersion: current.remoteVersion });
|
|
821
|
+
}
|
|
822
|
+
finally {
|
|
823
|
+
if (!opts.store)
|
|
824
|
+
try {
|
|
825
|
+
store.close();
|
|
826
|
+
}
|
|
827
|
+
catch { /* ignore */ }
|
|
828
|
+
}
|
|
829
|
+
});
|
|
830
|
+
}
|
|
792
831
|
/**
|
|
793
832
|
* Apply a profile to an SDK-owned card. Ownership declarations are SDK output:
|
|
794
833
|
* never reconstruct them from the form or replace the owned card with an
|