evolcore 0.0.41-test.0 → 0.0.41-test.1
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 +49 -0
- package/dist/agents/baseagent-availability.js +1 -1
- package/dist/agents/baseagent.js +20 -43
- package/dist/agents/claude-runner.js +177 -92
- package/dist/agents/codex-runner.js +84 -28
- package/dist/agents/ecagent-runner.js +1 -1
- package/dist/agents/gemini-runner.js +1 -1
- package/dist/aun/group/fs-download.js +39 -0
- package/dist/aun/group/identity.js +36 -21
- package/dist/aun/group/operations.js +5 -0
- package/dist/aun/msg/managed-operation.js +68 -7
- package/dist/aun/msg/p2p.js +5 -0
- package/dist/aun/service-proxy.js +36 -12
- package/dist/channels/aun.js +334 -20
- package/dist/channels/daemon.js +15 -1
- package/dist/cli/aun-commands.js +4 -20
- package/dist/cli/daemon-commands.js +678 -697
- package/dist/cli/fs-command.js +64 -2
- package/dist/cli/index.js +48 -4
- package/dist/cli/managed-command-guard.js +4 -0
- package/dist/cli/model.js +40 -40
- package/dist/cli/proxy-command.js +92 -0
- package/dist/cli/role.js +85 -0
- package/dist/config/access-policy.js +7 -2
- package/dist/config/boot-log.js +38 -1
- package/dist/config/config-field-policy.js +5 -32
- package/dist/config/config-manager.js +46 -39
- package/dist/config/config-operation-service.js +5 -19
- package/dist/config/contact-book-store.js +47 -21
- package/dist/config/contact-book.js +18 -12
- package/dist/config/contact-operation-service.js +3 -4
- package/dist/config/contact-request-service.js +11 -0
- package/dist/config/daemon-services.js +11 -0
- package/dist/config/gateway-config.js +88 -594
- package/dist/config/peer-role-resolver.js +13 -11
- package/dist/config/providers-config.js +12 -7
- package/dist/config/providers-import.js +3 -21
- package/dist/config/resolved-config-op.js +3 -0
- package/dist/config/role-command-service.js +166 -0
- package/dist/config/role-request-service.js +193 -0
- package/dist/config/schema-migration.js +686 -25
- package/dist/config-store.js +79 -3
- package/dist/contracts/ecweb-instance.js +41 -0
- package/dist/contracts/ecweb-service-protocol.js +3 -1
- package/dist/core/agent-runtime.js +1 -1
- package/dist/core/auth/agent-delegation.js +2 -1
- package/dist/core/auth/auth-gateway.js +1 -1
- package/dist/core/auth/authorization-audit.js +17 -6
- package/dist/core/auth/delegation-authorization.js +3 -1
- package/dist/core/auth/operation-authorizer.js +15 -0
- package/dist/core/auth/operation-catalog.js +31 -6
- package/dist/core/command/agent-control.js +3 -7
- package/dist/core/command/agent-storage-menu.js +5 -3
- package/dist/core/command/cli-intent-parser.js +2 -1
- package/dist/core/command/command-handler.js +48 -99
- package/dist/core/command/connect-menu.js +11 -3
- package/dist/core/command/data-root-resolver.js +5 -4
- package/dist/core/command/memory-slash.js +16 -8
- package/dist/core/command/menu-catalog.js +5 -6
- package/dist/core/command/menu-handler.js +49 -62
- package/dist/core/command/role-menu.js +147 -30
- package/dist/core/command/slash-handler.js +123 -254
- package/dist/core/daemon-control.js +8 -14
- package/dist/core/evolagent-registry.js +4 -4
- package/dist/core/evolagent.js +2 -2
- package/dist/core/inference/text-inference.js +31 -40
- package/dist/core/ipc-registration.js +6 -2
- package/dist/core/memory/consolidation-context.js +51 -5
- package/dist/core/memory/consolidation-ops-records.js +1 -1
- package/dist/core/memory/consolidation-trigger.js +189 -189
- package/dist/core/memory/consolidation.js +316 -29
- package/dist/core/memory/forget-log.js +96 -0
- package/dist/core/memory/index-manager.js +27 -5
- package/dist/core/memory/memory-admin.js +45 -5
- package/dist/core/memory/memory-writer.js +163 -18
- package/dist/core/memory/relation-idle-monitor.js +119 -58
- package/dist/core/memory/relation-sweep.js +44 -39
- package/dist/core/message/aun-ipc-sender.js +8 -2
- package/dist/core/message/im-renderer.js +7 -4
- package/dist/core/message/message-admission.js +89 -4
- package/dist/core/message/message-bridge.js +31 -18
- package/dist/core/message/response-engine.js +77 -8
- package/dist/core/model/catalog-service.js +4 -2
- package/dist/core/model/config-scope.js +24 -64
- package/dist/core/model/field-scope.js +1 -1
- package/dist/core/model/model-catalog.js +30 -41
- package/dist/core/model/model-diagnostics.js +4 -3
- package/dist/core/model/model-fallback.js +10 -7
- package/dist/core/model/model-permission.js +3 -2
- package/dist/core/ownership/owner-resolver.js +23 -21
- package/dist/core/permission/ec-command-parser.js +30 -2
- package/dist/core/permission/sandbox-runtime.js +18 -1
- package/dist/core/permission/tool-policy.js +14 -3
- package/dist/core/relation/peer-identity.js +64 -1
- package/dist/core/role/runtime-policy.js +72 -13
- package/dist/core/session/session-capsule.js +1 -1
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +20 -0
- package/dist/core/session/session-renew.js +3 -3
- package/dist/core/skill/index-generator.js +15 -5
- package/dist/core/system-session/memory.js +6 -1
- package/dist/core/thread/thread-service.js +19 -6
- package/dist/directory/owner-directory-admission.js +95 -0
- package/dist/directory/owner-directory-authorization.js +309 -0
- package/dist/directory/owner-directory-cache.js +635 -0
- package/dist/eck/kit-renderer.js +2 -2
- package/dist/ecweb/basic-settings-service.js +33 -40
- package/dist/ecweb/message-context-service.js +110 -0
- package/dist/index.js +76 -14
- package/dist/ipc.js +170 -12
- package/dist/paths.js +4 -0
- package/dist/proxy/command.js +122 -0
- package/dist/proxy/ipc-service.js +68 -0
- package/dist/proxy/manager.js +485 -0
- package/dist/proxy/service-supervisor.js +603 -0
- package/dist/response-system/engines/v1/proactive-flow.js +16 -6
- package/dist/utils/cross-platform.js +14 -0
- package/dist/utils/ecweb-supervisor.js +258 -83
- package/dist/utils/error-utils.js +2 -2
- package/dist/utils/logger.js +24 -5
- package/dist/utils/package-version-info.js +4 -2
- package/kits/docs/channels/aun.md +9 -0
- package/kits/docs/evolcore/agent.md +1 -1
- package/kits/docs/evolcore/config.md +17 -6
- package/kits/docs/evolcore/contact.md +3 -0
- package/kits/docs/evolcore/fs.md +11 -0
- package/kits/docs/evolcore/memory-architecture.md +2 -2
- package/kits/docs/evolcore/memory-consolidation.md +32 -8
- package/kits/docs/evolcore/memory.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +4 -0
- package/kits/docs/evolcore/model.md +23 -20
- package/kits/docs/evolcore/msg.md +4 -7
- package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
- package/kits/schemas/_meta.json +37 -4
- package/kits/schemas/agent-config.schema.13.json +8 -3
- package/kits/schemas/agent-config.schema.16.json +891 -0
- package/kits/schemas/daemon.schema.9.json +366 -0
- package/kits/schemas/defaults.schema.5.json +406 -127
- package/kits/schemas/relation-config.schema.11.json +260 -0
- package/kits/schemas/role-config.schema.1.json +7 -7
- package/kits/skills/.switches.json +3 -7
- package/kits/skills/ec-service-proxy/SKILL.md +118 -0
- package/kits/skills/ec-trigger/SKILL.md +13 -5
- package/kits/skills/personal-assistant/SKILL.md +176 -0
- package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
- package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
- package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
- package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
- package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
- package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
- package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
- package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
- package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
- package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
- package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
- package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
- package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
- package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
- package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
- package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
- package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
- package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
- package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
- package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
- package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
- package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
- package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
- package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
- package/kits/templates/memory-consolidation/forget.md +19 -6
- package/kits/templates/memory-consolidation/notes.md +1 -1
- package/kits/templates/memory-consolidation/profile.md +2 -2
- package/kits/templates/memory-consolidation/promote.md +20 -3
- package/kits/templates/roles/member.json +8 -1
- package/kits/templates/system-fragments/baseagent.md +2 -2
- package/kits/templates/system-fragments/memory.md +4 -4
- package/package.json +6 -2
|
@@ -3,10 +3,9 @@
|
|
|
3
3
|
* owns refreshes and snapshots. Runners in the daemon use that same instance.
|
|
4
4
|
*/
|
|
5
5
|
import path from 'node:path';
|
|
6
|
-
import { resolveAnthropicConfig, resolveEcagentConfig, resolveOpenaiConfig, loadCodexSettings } from '../../agents/baseagent.js';
|
|
7
|
-
import { buildModelRequestHeaders } from '../../agents/request-identity.js';
|
|
8
6
|
import { activeBaseagent } from './config-scope.js';
|
|
9
7
|
import { resolveEffective } from '../../config/config-manager.js';
|
|
8
|
+
import { readRuntimeEnvironmentVariable } from '../../config/runtime-env.js';
|
|
10
9
|
import { loadDefaults } from '../../config-store.js';
|
|
11
10
|
import net from 'node:net';
|
|
12
11
|
import fs from 'node:fs';
|
|
@@ -124,48 +123,38 @@ export function previewProviderCatalog(provider, requestedBaseagent) {
|
|
|
124
123
|
}
|
|
125
124
|
export function resolveCatalogContext(self, ba) {
|
|
126
125
|
const baseagent = ba || activeBaseagent(self);
|
|
127
|
-
const context = { scope: self || '<
|
|
128
|
-
const config = self ? resolveEffective({ self }, { cache: true
|
|
129
|
-
const block = (config
|
|
126
|
+
const context = { scope: self || '<none>', baseagent };
|
|
127
|
+
const config = self ? resolveEffective({ self }, { cache: true }) : loadDefaults();
|
|
128
|
+
const block = (config?.baseagents ?? {});
|
|
130
129
|
const selected = block[baseagent];
|
|
131
|
-
if (providerIsConfigured(selected)) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
queryParams: provider.queryParams,
|
|
143
|
-
modelOverrides: provider.modelOverrides,
|
|
144
|
-
});
|
|
145
|
-
return context;
|
|
146
|
-
}
|
|
147
|
-
try {
|
|
148
|
-
const cfg = { agents: block };
|
|
149
|
-
const resolved = baseagent === 'codex' ? resolveOpenaiConfig(cfg, block.codex)
|
|
150
|
-
: baseagent === 'claude' ? resolveAnthropicConfig(cfg, block.claude)
|
|
151
|
-
: baseagent === 'ecagent' ? resolveEcagentConfig(cfg, block.ecagent) : undefined;
|
|
152
|
-
if (resolved) {
|
|
153
|
-
Object.assign(context, { baseUrl: resolved.baseUrl, apiKey: resolved.apiKey, authType: 'authType' in resolved ? resolved.authType : undefined, queryParams: resolved.queryParams,
|
|
154
|
-
provider: 'provider' in resolved ? resolved.provider : undefined,
|
|
155
|
-
headers: buildModelRequestHeaders({ baseagent: baseagent, baseUrl: resolved.baseUrl, agentAid: self, configuredHeaders: resolved.headers }) });
|
|
130
|
+
if (!providerIsConfigured(selected)) {
|
|
131
|
+
// 没有显式 provider 时,回落到 base agent 自身的端点(环境变量),让目录也能
|
|
132
|
+
// 读到网关真实清单,而不是只剩内置候选。runtime-env 目前只管理 ANTHROPIC_*
|
|
133
|
+
// 这组变量,故仅对 claude 生效;其余 baseagent 或变量缺失时维持内置兜底。
|
|
134
|
+
if (baseagent === 'claude') {
|
|
135
|
+
const envBaseUrl = readRuntimeEnvironmentVariable('ANTHROPIC_BASE_URL', self).value;
|
|
136
|
+
if (envBaseUrl) {
|
|
137
|
+
const envApiKey = readRuntimeEnvironmentVariable('ANTHROPIC_AUTH_TOKEN', self).value
|
|
138
|
+
?? readRuntimeEnvironmentVariable('ANTHROPIC_API_KEY', self).value;
|
|
139
|
+
return { ...context, baseUrl: envBaseUrl, apiKey: envApiKey, style: 'claude' };
|
|
140
|
+
}
|
|
156
141
|
}
|
|
142
|
+
// 模型选择只在 Agent 级且必须指向 provider;没有 provider 就没有目录可查。
|
|
143
|
+
return { ...context, configUnavailable: true };
|
|
157
144
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
145
|
+
const provider = resolveProviderServiceForBaseagent(selected.provider, baseagent);
|
|
146
|
+
Object.assign(context, {
|
|
147
|
+
provider: provider.providerId,
|
|
148
|
+
providerId: provider.providerId,
|
|
149
|
+
providerServiceType: provider.serviceType,
|
|
150
|
+
catalogPath: provider.catalogPath,
|
|
151
|
+
style: provider.style,
|
|
152
|
+
baseUrl: provider.baseUrl,
|
|
153
|
+
apiKey: provider.apiKey,
|
|
154
|
+
headers: provider.headers,
|
|
155
|
+
queryParams: provider.queryParams,
|
|
156
|
+
modelOverrides: provider.modelOverrides,
|
|
157
|
+
});
|
|
169
158
|
return context;
|
|
170
159
|
}
|
|
171
160
|
/** Query the catalog for a host-level default connection, without Agent scope. */
|
|
@@ -19,7 +19,7 @@ async function fetchWithTimeout(url, opts, timeoutMs) {
|
|
|
19
19
|
}
|
|
20
20
|
function resolveGatewayCreds(self, baseagent) {
|
|
21
21
|
try {
|
|
22
|
-
const config = self ? resolveEffective({ self }, { cache: true
|
|
22
|
+
const config = self ? resolveEffective({ self }, { cache: true }) : { baseagents: {} };
|
|
23
23
|
const block = config.baseagents || {};
|
|
24
24
|
if (baseagent === 'codex') {
|
|
25
25
|
const codexCfg = block.codex || {};
|
|
@@ -155,7 +155,8 @@ export async function runModelCheck(input) {
|
|
|
155
155
|
log(catalog.freshness !== 'fresh'
|
|
156
156
|
? { label: '模型列表', ok: false, detail: `目录已降级,来源 ${catalog.source}(${modelIds.length} 个)` }
|
|
157
157
|
: { label: '模型列表', ok: true, detail: `来源: ${catalog.source},共 ${modelIds.length} 个模型` });
|
|
158
|
-
|
|
158
|
+
// 模型只在 Agent 级配置,不按对端解析。
|
|
159
|
+
const selector = { self: input.self };
|
|
159
160
|
const modelResolution = resolveEffectiveFieldWithSource(`baseagents.${input.baseagent}.model`, selector, { cache: true });
|
|
160
161
|
const modelDecision = constrainResolvedModelForRole({
|
|
161
162
|
selfAid: input.self,
|
|
@@ -169,7 +170,7 @@ export async function runModelCheck(input) {
|
|
|
169
170
|
: modelResolution.source?.target;
|
|
170
171
|
log(configuredModel
|
|
171
172
|
? { label: '配置模型', ok: true, detail: `${configuredModel}(来源: ${configuredModelSource ?? '未知'})` }
|
|
172
|
-
: { label: '配置模型', ok:
|
|
173
|
+
: { label: '配置模型', ok: false, detail: 'Agent 级未配置模型,该 Agent 无模型可用(owner/admin 用 /model 设置)' });
|
|
173
174
|
const probeResults = [];
|
|
174
175
|
if (baseUrl) {
|
|
175
176
|
const aliases = new Map();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { catalogEfforts, getCatalog, getProviderCatalog, resolveCatalogModel } from './model-catalog.js';
|
|
2
|
-
import {
|
|
2
|
+
import { resolveEffective } from '../../config/config-manager.js';
|
|
3
3
|
import { providerServiceTypeForBaseagent, providerServiceTypeForPurpose, resolveServiceSelection } from '../../config/providers.js';
|
|
4
4
|
export const MAX_FALLBACK_MODELS = 3;
|
|
5
5
|
function isRecord(value) {
|
|
@@ -42,9 +42,12 @@ function configuredFallbacks(raw) {
|
|
|
42
42
|
}
|
|
43
43
|
return { candidates, rejected };
|
|
44
44
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
45
|
+
/** 降级链只在 Agent 级 baseagents.<ba>.fallback 配置;没有 Agent 作用域就没有降级链。 */
|
|
46
|
+
export function configuredFallbackModels(baseagent, selfAid) {
|
|
47
|
+
if (!selfAid)
|
|
48
|
+
return { candidates: [], rejected: [] };
|
|
49
|
+
const effective = resolveEffective({ self: selfAid }, { cache: true });
|
|
50
|
+
const block = isRecord(effective?.baseagents) ? effective.baseagents[baseagent] : undefined;
|
|
48
51
|
return configuredFallbacks(isRecord(block) ? block.fallback : undefined);
|
|
49
52
|
}
|
|
50
53
|
async function eligibleCandidates(input) {
|
|
@@ -115,12 +118,12 @@ async function eligibleCandidates(input) {
|
|
|
115
118
|
}
|
|
116
119
|
export async function eligibleFallbackModels(input) {
|
|
117
120
|
const effective = input.selfAid
|
|
118
|
-
? resolveEffective({ self: input.selfAid }, { cache: true
|
|
119
|
-
:
|
|
121
|
+
? resolveEffective({ self: input.selfAid }, { cache: true })
|
|
122
|
+
: undefined;
|
|
120
123
|
const selection = effective?.baseagents?.[input.baseagent];
|
|
121
124
|
return eligibleCandidates({
|
|
122
125
|
...input,
|
|
123
|
-
configured: configuredFallbackModels(input.baseagent),
|
|
126
|
+
configured: configuredFallbackModels(input.baseagent, input.selfAid),
|
|
124
127
|
serviceType: input.baseagent,
|
|
125
128
|
catalogBaseagent: input.baseagent,
|
|
126
129
|
catalogProviderServiceType: selection?.providerServiceType,
|
|
@@ -88,13 +88,14 @@ export function validateModelSelectionForRole(opts) {
|
|
|
88
88
|
return { ok: true, model: targetModel };
|
|
89
89
|
}
|
|
90
90
|
export function constrainResolvedModelForRole(opts) {
|
|
91
|
+
// 角色策略只约束 Agent 级已配置的模型,不提供模型:Agent 级没有模型就是无模型可用。
|
|
92
|
+
if (!opts.model)
|
|
93
|
+
return { model: undefined, constrained: false };
|
|
91
94
|
const permission = getRoleModelPermission(opts.role, opts.baseagent, opts.selfAid);
|
|
92
95
|
if (!permission.constrained)
|
|
93
96
|
return { model: opts.model, constrained: false };
|
|
94
97
|
if (!permission.allowOverride)
|
|
95
98
|
return { model: permission.defaultModel || opts.model, constrained: true };
|
|
96
|
-
if (!opts.model)
|
|
97
|
-
return { model: permission.defaultModel, constrained: true };
|
|
98
99
|
if (isModelAllowedForRoleBaseagent(opts.role, opts.baseagent, opts.model, opts.resolveModelId, opts.selfAid)) {
|
|
99
100
|
return { model: opts.model, constrained: false };
|
|
100
101
|
}
|
|
@@ -9,8 +9,6 @@ import { logger } from '../../utils/logger.js';
|
|
|
9
9
|
import { hasTrustedPrincipal } from '../auth/authenticated-actor.js';
|
|
10
10
|
export const OWNERSHIP_CACHE_MAX_AGE_MS = 30 * 60_000;
|
|
11
11
|
export const OWNERSHIP_AUTHORIZATION_MAX_AGE_MS = 5 * 60_000;
|
|
12
|
-
// Background refreshes should heal a short outage without retrying on every tool call.
|
|
13
|
-
const OWNERSHIP_BACKGROUND_REFRESH_MIN_INTERVAL_MS = 60_000;
|
|
14
12
|
const CREATION_BIND_OPERATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
15
13
|
/** Only use the task returned by this create's bind call. Never select a latest task. */
|
|
16
14
|
export function creationOwnershipBinding(task, subjectAid, ownerAid) {
|
|
@@ -298,20 +296,11 @@ export class OwnerResolver {
|
|
|
298
296
|
const initialEpoch = subject.epoch;
|
|
299
297
|
const initialCheckedAt = subject.view.checkedAt;
|
|
300
298
|
const maxAgeMs = options.maxAgeMs ?? this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS;
|
|
301
|
-
const isFresh = () =>
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
&& checkedAt !== undefined && checkedAt <= now && (validUntil ?? 0) > now
|
|
306
|
-
&& now - checkedAt < maxAgeMs;
|
|
307
|
-
};
|
|
308
|
-
if (!refreshing && !options.force && isFresh()) {
|
|
309
|
-
if (options.allowTransient
|
|
310
|
-
&& this.now() - (subject.lastRefreshAttemptAt ?? 0) >= OWNERSHIP_BACKGROUND_REFRESH_MIN_INTERVAL_MS) {
|
|
311
|
-
this.schedule(subjectAid, subject, true);
|
|
312
|
-
}
|
|
299
|
+
const isFresh = () => this.isCacheFresh(subject, maxAgeMs);
|
|
300
|
+
// A valid cache never schedules a supplementary consensus check; identity
|
|
301
|
+
// verification only runs when the cache is stale or an operation forces it.
|
|
302
|
+
if (!refreshing && !options.force && isFresh())
|
|
313
303
|
return this.snapshot(subjectAid);
|
|
314
|
-
}
|
|
315
304
|
const attemptId = inFlight?.attemptId ?? ++subject.query;
|
|
316
305
|
const attemptedAt = inFlight?.attemptedAt ?? this.now();
|
|
317
306
|
const promise = refreshing ?? this.refreshSubject(subjectAid, subject, attemptId, attemptedAt);
|
|
@@ -339,7 +328,6 @@ export class OwnerResolver {
|
|
|
339
328
|
}
|
|
340
329
|
async refreshSubject(subjectAid, subject, attemptId, attemptedAt) {
|
|
341
330
|
const client = subject.client;
|
|
342
|
-
subject.lastRefreshAttemptAt = attemptedAt;
|
|
343
331
|
if (!client || !subject.view.connected) {
|
|
344
332
|
const reason = 'Subject AID has no connected SDK client';
|
|
345
333
|
this.handleRefreshFailure(subjectAid, subject, { code: 'CLIENT_DISCONNECTED', message: reason }, attemptedAt, attemptId);
|
|
@@ -551,10 +539,17 @@ export class OwnerResolver {
|
|
|
551
539
|
}
|
|
552
540
|
async status(subjectAid) {
|
|
553
541
|
const subject = this.subject(subjectAid);
|
|
542
|
+
// Status display reuses the resolve snapshot; consensus verification is
|
|
543
|
+
// reserved for operations that actually depend on Owner permission.
|
|
544
|
+
if (subject.client && subject.view.connected)
|
|
545
|
+
return this.refresh(subjectAid);
|
|
546
|
+
// A fresh snapshot survives transport loss; serve it instead of loading a
|
|
547
|
+
// short-lived client. Only a stale unattached subject needs a live check.
|
|
548
|
+
if (this.isCacheFresh(subject, this.options.lifetimeMs ?? OWNERSHIP_CACHE_MAX_AGE_MS)) {
|
|
549
|
+
return this.snapshot(subjectAid);
|
|
550
|
+
}
|
|
554
551
|
const generation = subject.generation;
|
|
555
|
-
return this.withSubjectClient(subjectAid, async (client
|
|
556
|
-
if (attached)
|
|
557
|
-
return this.refresh(subjectAid, { force: true });
|
|
552
|
+
return this.withSubjectClient(subjectAid, async (client) => {
|
|
558
553
|
const consensus = await client.checkOwnershipConsensus(subjectAid);
|
|
559
554
|
if (subject.generation !== generation) {
|
|
560
555
|
throw new OwnershipError('CLIENT_REPLACED', 'Subject state changed during status query; retry');
|
|
@@ -563,6 +558,13 @@ export class OwnerResolver {
|
|
|
563
558
|
return this.snapshot(subjectAid);
|
|
564
559
|
});
|
|
565
560
|
}
|
|
561
|
+
isCacheFresh(subject, maxAgeMs) {
|
|
562
|
+
const { checkedAt, validUntil, consensusStatus } = subject.view;
|
|
563
|
+
const now = this.now();
|
|
564
|
+
return consensusStatus !== 'unavailable' && consensusStatus !== 'not_applicable'
|
|
565
|
+
&& checkedAt !== undefined && checkedAt <= now && (validUntil ?? 0) > now
|
|
566
|
+
&& now - checkedAt < maxAgeMs;
|
|
567
|
+
}
|
|
566
568
|
async withSubjectClient(subjectAid, operation) {
|
|
567
569
|
const subject = this.subject(subjectAid);
|
|
568
570
|
if (subject.client && subject.view.connected)
|
|
@@ -799,12 +801,12 @@ export class OwnerResolver {
|
|
|
799
801
|
}
|
|
800
802
|
}
|
|
801
803
|
}
|
|
802
|
-
schedule(subjectAid, subject
|
|
804
|
+
schedule(subjectAid, subject) {
|
|
803
805
|
if (subject.timer || !subject.client || !subject.view.connected)
|
|
804
806
|
return;
|
|
805
807
|
subject.timer = setTimeout(() => {
|
|
806
808
|
subject.timer = undefined;
|
|
807
|
-
void this.refresh(subjectAid, { force: true, allowTransient }).catch(error => {
|
|
809
|
+
void this.refresh(subjectAid, { force: true, allowTransient: true }).catch(error => {
|
|
808
810
|
logger.warn(`[ownership] Event refresh failed for ${subjectAid}: ${error instanceof Error ? error.message : String(error)}`);
|
|
809
811
|
});
|
|
810
812
|
}, 0);
|
|
@@ -25,11 +25,13 @@ export function parseJsonObjectArgument(raw, optionName = '--payload') {
|
|
|
25
25
|
return parsed;
|
|
26
26
|
}
|
|
27
27
|
export function buildCanonicalEvolcoreExecutionSpec(input) {
|
|
28
|
+
const argv = normalizeEvolcoreCommandArgv(input.argv);
|
|
29
|
+
canonicalizeLocalFilePathFlags(argv);
|
|
28
30
|
const spec = {
|
|
29
31
|
version: 1,
|
|
30
32
|
dialect: input.dialect,
|
|
31
33
|
wrapper: input.wrapper,
|
|
32
|
-
argv
|
|
34
|
+
argv,
|
|
33
35
|
};
|
|
34
36
|
if (input.cwd !== undefined)
|
|
35
37
|
spec.cwd = input.cwd;
|
|
@@ -335,7 +337,7 @@ const EVOLCORE_SUBCOMMANDS = new Set([
|
|
|
335
337
|
'fs', 'gateway', 'group', 'handoff', 'init', 'link-rules', 'logs', 'menu-client',
|
|
336
338
|
'mode', 'model', 'msg', 'mv', 'net', 'queue', 'response', 'restart',
|
|
337
339
|
'restart-monitor', 'rpc', 'start', 'stats', 'status', 'stop', 'storage', 'task',
|
|
338
|
-
'trigger', 'version', 'watch', 'session',
|
|
340
|
+
'trigger', 'proxy', 'version', 'watch', 'session',
|
|
339
341
|
]);
|
|
340
342
|
// Development/install entrypoints that are part of this repository's CLI.
|
|
341
343
|
// Only these exact relative paths are canonicalized; arbitrary Node scripts
|
|
@@ -914,6 +916,27 @@ function canonicalizeHandoffText(argv) {
|
|
|
914
916
|
argv[index] = decodeEvolcoreInlineText(argv[index]);
|
|
915
917
|
}
|
|
916
918
|
}
|
|
919
|
+
const LOCAL_FILE_VALUE_FLAGS = new Set(['--file', '--text-from-file', '--payload-file']);
|
|
920
|
+
function normalizeWindowsFilePath(value) {
|
|
921
|
+
if (process.platform !== 'win32' || !/^[A-Za-z]:[\\/]/u.test(value))
|
|
922
|
+
return value;
|
|
923
|
+
return value.replace(/\\{2,}/gu, '\\').replace(/\/{2,}/gu, '/');
|
|
924
|
+
}
|
|
925
|
+
function canonicalizeLocalFilePathFlags(argv) {
|
|
926
|
+
for (let index = 2; index < argv.length; index++) {
|
|
927
|
+
if (argv[index] === '--')
|
|
928
|
+
break;
|
|
929
|
+
const inline = argv[index].match(/^(--(?:file|text-from-file|payload-file))=(.*)$/u);
|
|
930
|
+
if (inline) {
|
|
931
|
+
argv[index] = `${inline[1]}=${normalizeWindowsFilePath(inline[2])}`;
|
|
932
|
+
continue;
|
|
933
|
+
}
|
|
934
|
+
if (!LOCAL_FILE_VALUE_FLAGS.has(argv[index]) || argv[index + 1] === undefined)
|
|
935
|
+
continue;
|
|
936
|
+
argv[index + 1] = normalizeWindowsFilePath(argv[index + 1]);
|
|
937
|
+
index++;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
917
940
|
/**
|
|
918
941
|
* Convert an EC invocation to the one argv representation shared by approval,
|
|
919
942
|
* delegation hashing, IPC, and command execution. Shell syntax is already
|
|
@@ -926,6 +949,7 @@ export function canonicalizeEvolcoreCommandArgv(argv) {
|
|
|
926
949
|
if (canonical[0] !== 'ec')
|
|
927
950
|
return canonical;
|
|
928
951
|
const result = [...canonical];
|
|
952
|
+
canonicalizeLocalFilePathFlags(result);
|
|
929
953
|
const command = result[1];
|
|
930
954
|
const subcommand = result[2];
|
|
931
955
|
if (command === 'agent') {
|
|
@@ -2545,6 +2569,10 @@ export function parseCodexExecToolCommand(input) {
|
|
|
2545
2569
|
function classifyCompositeProactiveSend(commandText, options) {
|
|
2546
2570
|
const classified = classifyEvolcoreShellCommand(commandText, options);
|
|
2547
2571
|
if (classified.kind === 'cd-prefixed' || classified.kind === 'bounded-output') {
|
|
2572
|
+
// 带尾部命令(suffixArgv)的结构不允许作为 proactive send 放行:
|
|
2573
|
+
// 尾部段可以是任意 echo/pwd,拼接意图不可证。
|
|
2574
|
+
if (classified.command.suffixArgv?.length)
|
|
2575
|
+
return null;
|
|
2548
2576
|
const argv = normalizeEvolcoreCommandArgv(classified.command.argv);
|
|
2549
2577
|
if (argv[0] === 'ec')
|
|
2550
2578
|
return { ok: true, argv };
|
|
@@ -115,6 +115,22 @@ export function isSandboxInitializationFailure(error, stderr = []) {
|
|
|
115
115
|
|| /(?:^|\n)\s*bwrap:\s*(?:can't|cannot) create (?:file|directory) at [^\n]+: read-only file system/.test(text)
|
|
116
116
|
|| /(?:^|\n)\s*bwrap:\s*(?:can't|cannot) mkdir parents for [^\n]+: read-only file system/.test(text);
|
|
117
117
|
}
|
|
118
|
+
/**
|
|
119
|
+
* Recognize failures from a task runner's nested sandbox. The outer EvolCore
|
|
120
|
+
* H-class guard is already running when this is used, so generic outer guard
|
|
121
|
+
* launch failures must not be treated as safe fallback candidates.
|
|
122
|
+
*/
|
|
123
|
+
export function isNestedSandboxInitializationFailure(error, stderr = []) {
|
|
124
|
+
const text = [error instanceof Error ? error.message : String(error ?? ''), ...stderr]
|
|
125
|
+
.join('\n')
|
|
126
|
+
.toLowerCase();
|
|
127
|
+
return text.includes(CODEX_SANDBOX_USER_NAMESPACE_UNAVAILABLE)
|
|
128
|
+
|| text.includes(CODEX_SANDBOX_USER_NAMESPACE_DISABLED_BY_APPARMOR)
|
|
129
|
+
|| /fs sandbox helper failed/.test(text)
|
|
130
|
+
|| /failed to initialize session[\s\S]*sandbox/.test(text)
|
|
131
|
+
|| /(?:apply-seccomp|seccomp)[\s\S]*(?:uid_map|gid_map|operation not permitted|permission denied)/.test(text)
|
|
132
|
+
|| /(?:uid_map|gid_map)[\s\S]*(?:operation not permitted|permission denied)/.test(text);
|
|
133
|
+
}
|
|
118
134
|
export function isCodexSandboxUserNamespaceFailure(error) {
|
|
119
135
|
const record = error && typeof error === 'object'
|
|
120
136
|
? error
|
|
@@ -318,7 +334,8 @@ export function formatCodexSandboxAvailability(check) {
|
|
|
318
334
|
return `Codex Linux sandbox check not applicable on ${check.platform}`;
|
|
319
335
|
if (check.status === 'missing') {
|
|
320
336
|
return 'Codex Linux sandbox is unavailable: bubblewrap (bwrap) was not found; '
|
|
321
|
-
+ 'install or provision the Codex sandbox runtime.
|
|
337
|
+
+ 'install or provision the Codex nested sandbox runtime. Managed Linux sessions may retry '
|
|
338
|
+
+ 'behind the EvolCore H-class guard; direct app-server callers remain fail-closed.';
|
|
322
339
|
}
|
|
323
340
|
const apparmor = check.apparmorRestrictsUnprivilegedUserns === true
|
|
324
341
|
? ' AppArmor restricts unprivileged user namespaces on this host; the probe below confirms whether the active profile permits Codex.'
|
|
@@ -2107,7 +2107,7 @@ export function checkLClassWrite(toolName, input, context) {
|
|
|
2107
2107
|
behavior: 'deny',
|
|
2108
2108
|
message: context?.permissionMode === 'readonly'
|
|
2109
2109
|
? '🔒 只读模式:visitor 最低权限不允许读取 L-class 路径'
|
|
2110
|
-
:
|
|
2110
|
+
: `🔒 L-class 路径允许读取,但当前 Bash 命令无法证明为只读${protectedOperands.analysis.kind === 'unproven' ? `(原因码:${protectedOperands.analysis.reason})` : ''},已拒绝执行。请改用受控的 EvolCore 读取命令或白名单只读命令`,
|
|
2111
2111
|
matchedPath: protectedOperands.lClassPath,
|
|
2112
2112
|
};
|
|
2113
2113
|
}
|
|
@@ -2369,6 +2369,7 @@ export function checkBashDescription(toolName, input) {
|
|
|
2369
2369
|
/** Shared fail-closed preflight used before runner-specific mode and approval handling. */
|
|
2370
2370
|
export function evaluateToolPreflight(toolName, input, context) {
|
|
2371
2371
|
let applyPatchFileChanges;
|
|
2372
|
+
let protectedPolicyCommand;
|
|
2372
2373
|
const managedPathCheck = checkManagedTempToolPaths(toolName, input, managedTempOptions(context));
|
|
2373
2374
|
if (managedPathCheck.kind === 'deny') {
|
|
2374
2375
|
const currentTmpDir = resolveManagedTempDir(managedTempOptions(context).env);
|
|
@@ -2418,6 +2419,13 @@ export function evaluateToolPreflight(toolName, input, context) {
|
|
|
2418
2419
|
?? (explicitCommandArgv ? undefined : resolveCodexShellCarrierString(command));
|
|
2419
2420
|
const wrappedCommand = stringShellCarrier?.parseFailure ? undefined : stringShellCarrier?.command;
|
|
2420
2421
|
const policyCommand = wrappedCommand ?? commandForPolicy;
|
|
2422
|
+
// The class checks must inspect the same inner command used by command
|
|
2423
|
+
// classification. Otherwise Codex's outer `bash -lc` carrier makes a
|
|
2424
|
+
// valid single read look like an unsupported composite shell command.
|
|
2425
|
+
protectedPolicyCommand = wrappedCommand
|
|
2426
|
+
?? (!shellCarrier && explicitCommandArgv
|
|
2427
|
+
? explicitCommandArgv.map(quotePosixShellArg).join(' ')
|
|
2428
|
+
: undefined);
|
|
2421
2429
|
if (context.sessionId && /^\s*(?:command\s+-v|which|type)\s+ec\s*$/i.test(policyCommand)) {
|
|
2422
2430
|
return {
|
|
2423
2431
|
behavior: 'deny',
|
|
@@ -2693,7 +2701,10 @@ export function evaluateToolPreflight(toolName, input, context) {
|
|
|
2693
2701
|
? { ...checkedInput, fileChanges: applyPatchFileChanges }
|
|
2694
2702
|
: checkedInput;
|
|
2695
2703
|
const policyToolName = applyPatchFileChanges ? 'FileChange' : toolName;
|
|
2696
|
-
const
|
|
2704
|
+
const protectedPolicyInput = policyToolName === 'Bash' && protectedPolicyCommand
|
|
2705
|
+
? { ...policyInput, command: protectedPolicyCommand }
|
|
2706
|
+
: policyInput;
|
|
2707
|
+
const hClass = checkHClassWrite(policyToolName, protectedPolicyInput, {
|
|
2697
2708
|
sessionId: context.sessionId,
|
|
2698
2709
|
channel: context.channel,
|
|
2699
2710
|
peerId: context.userId,
|
|
@@ -2710,7 +2721,7 @@ export function evaluateToolPreflight(toolName, input, context) {
|
|
|
2710
2721
|
if (hClass.behavior === 'deny') {
|
|
2711
2722
|
return { behavior: 'deny', input: checkedInput, message: hClass.message, policyCode: 'h_class_protection', matchedPath: hClass.matchedPath };
|
|
2712
2723
|
}
|
|
2713
|
-
const lClass = checkLClassWrite(policyToolName,
|
|
2724
|
+
const lClass = checkLClassWrite(policyToolName, protectedPolicyInput, {
|
|
2714
2725
|
sessionId: context.sessionId,
|
|
2715
2726
|
channel: context.channel,
|
|
2716
2727
|
peerId: context.userId,
|
|
@@ -66,7 +66,10 @@ import * as path from 'path';
|
|
|
66
66
|
import * as crypto from 'crypto';
|
|
67
67
|
import { parse as parseYaml } from 'yaml';
|
|
68
68
|
import { logger } from '../../utils/logger.js';
|
|
69
|
-
import { agentMdPath } from '../../paths.js';
|
|
69
|
+
import { agentDir as resolveAgentDir, agentMdPath } from '../../paths.js';
|
|
70
|
+
import { ConfigTarget, mutateConfig, read } from '../../config/config-manager.js';
|
|
71
|
+
import { isValidAid } from '../../aun/aid/validation.js';
|
|
72
|
+
import { resolveAunTargetKind, verifiedPeerType, } from '../../aun/group/identity.js';
|
|
70
73
|
/**
|
|
71
74
|
* peerKey: 关系层路由键,格式 `<channelType>#<urlEncode(channelId)>`。
|
|
72
75
|
* 群聊场景下 channelId = groupId,所有发言者共用同一个 peerKey。
|
|
@@ -83,6 +86,58 @@ export function parsePeerKey(key) {
|
|
|
83
86
|
channelId: decodeURIComponent(key.slice(idx + 1)),
|
|
84
87
|
};
|
|
85
88
|
}
|
|
89
|
+
/** Read type evidence without network access or any AID-shape fallback. */
|
|
90
|
+
export function readAunPeerKind(selfAid, peerAid, options = {}) {
|
|
91
|
+
if (!isValidAid(selfAid) || !isValidAid(peerAid)) {
|
|
92
|
+
return { kind: 'unknown', reason: 'invalid', sources: [] };
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
const relation = options.relation !== undefined ? options.relation
|
|
96
|
+
: read(ConfigTarget.Relation, { self: selfAid, peerKey: formatPeerKey('aun', peerAid) });
|
|
97
|
+
return resolveAunTargetKind({
|
|
98
|
+
routeKind: options.routeKind,
|
|
99
|
+
targetKind: relation?.targetKind,
|
|
100
|
+
verifiedType: verifiedPeerType(peerAid, PeerIdentityCache.get('aun', peerAid, resolveAgentDir(selfAid))),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return { kind: 'unknown', reason: 'unavailable', sources: [] };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Fetch and cache a verified card only when local evidence is missing. Never resolve a conflict by guessing. */
|
|
108
|
+
export async function resolveAunPeerKind(selfAid, peerAid, options = {}) {
|
|
109
|
+
const current = readAunPeerKind(selfAid, peerAid, options);
|
|
110
|
+
if (current.reason !== 'missing')
|
|
111
|
+
return current;
|
|
112
|
+
try {
|
|
113
|
+
const { agentmdGet } = await import('../../aun/aid/agentmd.js');
|
|
114
|
+
const result = await agentmdGet(peerAid, { withVerification: true });
|
|
115
|
+
if (result.verification.status !== 'verified')
|
|
116
|
+
return { ...current, reason: 'unavailable' };
|
|
117
|
+
const metadata = parseAgentMdFrontmatter(result.content);
|
|
118
|
+
if (metadata.aid !== peerAid || typeof metadata.type !== 'string' || !metadata.type.trim()) {
|
|
119
|
+
return { kind: 'unknown', reason: 'invalid', sources: [] };
|
|
120
|
+
}
|
|
121
|
+
PeerIdentityCache.cacheVerifiedAgentMd('aun', peerAid, resolveAgentDir(selfAid), result.content);
|
|
122
|
+
// Re-read relation metadata because it may have changed during the remote lookup.
|
|
123
|
+
return readAunPeerKind(selfAid, peerAid, options);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return { ...current, reason: 'unavailable' };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/** Persist a trusted runtime kind, without overwriting conflicting evidence. */
|
|
130
|
+
export function recordAunPeerRoute(selfAid, peerAid, routeKind) {
|
|
131
|
+
const current = readAunPeerKind(selfAid, peerAid, { routeKind });
|
|
132
|
+
if (current.kind !== routeKind)
|
|
133
|
+
return current;
|
|
134
|
+
return mutateConfig(ConfigTarget.Relation, { self: selfAid, peerKey: formatPeerKey('aun', peerAid) }, relation => {
|
|
135
|
+
const resolution = readAunPeerKind(selfAid, peerAid, { routeKind, relation });
|
|
136
|
+
if (resolution.kind === routeKind)
|
|
137
|
+
relation.targetKind = routeKind;
|
|
138
|
+
return resolution;
|
|
139
|
+
}).value;
|
|
140
|
+
}
|
|
86
141
|
/**
|
|
87
142
|
* 对端身份缓存管理器
|
|
88
143
|
*/
|
|
@@ -114,6 +169,14 @@ export class PeerIdentityCache {
|
|
|
114
169
|
return null;
|
|
115
170
|
}
|
|
116
171
|
}
|
|
172
|
+
/** Internal callers must pass bytes returned by agentmdGet with verification.status=verified. */
|
|
173
|
+
static cacheVerifiedAgentMd(channelType, peerId, agentDir, content) {
|
|
174
|
+
const metadata = parseAgentMdFrontmatter(content);
|
|
175
|
+
if (metadata.aid !== peerId || typeof metadata.type !== 'string' || !metadata.type.trim()) {
|
|
176
|
+
throw new Error('Verified agent.md must declare the requested AID and its type');
|
|
177
|
+
}
|
|
178
|
+
return this.updateFromAgentMd(channelType, peerId, agentDir, content, Date.now(), 'agentmd');
|
|
179
|
+
}
|
|
117
180
|
/** Expire only the freshness check; retain the last snapshot and its trust level. */
|
|
118
181
|
static invalidate(channelType, peerId, agentDir) {
|
|
119
182
|
const cached = this.get(channelType, peerId, agentDir);
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { getRoleDefinition } from '../../config/roles.js';
|
|
2
2
|
import { PUBLIC_PERMISSION_MODES } from '../permission/mode.js';
|
|
3
|
-
import { ConfigTarget, read } from '../../config/config-manager.js';
|
|
3
|
+
import { ConfigTarget, mutateConfig, 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
7
|
import { isTopicSession } from '../thread/topic-id.js';
|
|
8
|
+
import { formatPeerKey } from '../relation/peer-identity.js';
|
|
9
|
+
import { logger } from '../../utils/logger.js';
|
|
8
10
|
const PERMISSION_MODE_AUTHORITY = {
|
|
9
11
|
readonly: 0,
|
|
10
12
|
auto: 1,
|
|
@@ -161,30 +163,85 @@ export function agentFullAccessStatus(agentAid, principalId) {
|
|
|
161
163
|
return { enabled, eligible, effective: enabled && eligible };
|
|
162
164
|
}
|
|
163
165
|
export function sessionFullAccessStatus(session, principalId) {
|
|
164
|
-
const override = session.metadata?.sessionFullAccess;
|
|
165
166
|
const agentStatus = session.selfAID ? agentFullAccessStatus(session.selfAID, principalId) : {
|
|
166
167
|
enabled: false, eligible: false, effective: false,
|
|
167
168
|
};
|
|
168
|
-
|
|
169
|
-
|
|
169
|
+
// Agent policy is the global switch. Once enabled for an eligible owner it
|
|
170
|
+
// takes precedence over any per-main-session or per-topic /fa state.
|
|
171
|
+
const override = readSessionFullAccessOverride(session);
|
|
172
|
+
const localEnabled = override?.enabled === true;
|
|
173
|
+
const scope = isTopicSession(session) ? 'session' : 'relation';
|
|
174
|
+
if (agentStatus.enabled) {
|
|
175
|
+
return {
|
|
176
|
+
...agentStatus, effective: agentStatus.effective && session.chatType === 'private',
|
|
177
|
+
inherited: true, globalEnabled: true, localEnabled, scope, source: 'agent', mutable: false,
|
|
178
|
+
};
|
|
170
179
|
}
|
|
171
|
-
if (!override
|
|
172
|
-
return {
|
|
180
|
+
if (!override) {
|
|
181
|
+
return {
|
|
182
|
+
enabled: false, eligible: agentStatus.eligible, effective: false,
|
|
183
|
+
inherited: false, globalEnabled: false, localEnabled: false, scope, source: scope, mutable: true,
|
|
184
|
+
};
|
|
173
185
|
}
|
|
174
186
|
const eligible = !!session.selfAID && isAgentFullAccessOwner(session.selfAID, principalId);
|
|
175
187
|
return {
|
|
176
188
|
enabled: override.enabled === true,
|
|
177
189
|
eligible,
|
|
178
|
-
effective: override.enabled === true && eligible && principalId === override.authorizedBy
|
|
190
|
+
effective: override.enabled === true && eligible && principalId === override.authorizedBy
|
|
191
|
+
&& session.chatType === 'private',
|
|
179
192
|
inherited: false,
|
|
193
|
+
globalEnabled: false,
|
|
194
|
+
localEnabled,
|
|
195
|
+
scope,
|
|
196
|
+
source: scope,
|
|
197
|
+
mutable: true,
|
|
180
198
|
authorizedBy: override.authorizedBy,
|
|
181
199
|
};
|
|
182
200
|
}
|
|
183
|
-
|
|
184
|
-
|
|
201
|
+
/** Read the local /fa switch without applying the Agent-level global switch. */
|
|
202
|
+
export function readSessionFullAccessOverride(session) {
|
|
203
|
+
let value = session.metadata?.sessionFullAccess;
|
|
204
|
+
if (!isTopicSession(session)) {
|
|
205
|
+
const selector = mainSessionFullAccessSelector(session);
|
|
206
|
+
if (!selector)
|
|
207
|
+
return undefined;
|
|
208
|
+
try {
|
|
209
|
+
value = read(ConfigTarget.Relation, selector, { cache: false })?.sessionFullAccess;
|
|
210
|
+
}
|
|
211
|
+
catch (error) {
|
|
212
|
+
logger.warn(`[FullAccess] Cannot read main-session policy for ${session.id}: ${error instanceof Error ? error.message : String(error)}`);
|
|
213
|
+
return undefined;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
217
|
+
return undefined;
|
|
218
|
+
const config = value;
|
|
219
|
+
return typeof config.enabled === 'boolean'
|
|
220
|
+
&& typeof config.authorizedBy === 'string' && !!config.authorizedBy.trim()
|
|
221
|
+
? { enabled: config.enabled, authorizedBy: config.authorizedBy }
|
|
222
|
+
: undefined;
|
|
223
|
+
}
|
|
224
|
+
function mainSessionFullAccessSelector(session) {
|
|
225
|
+
const peerId = session.channelId;
|
|
226
|
+
if (isTopicSession(session) || session.chatType !== 'private' || !session.selfAID || !peerId)
|
|
227
|
+
return undefined;
|
|
228
|
+
return { self: session.selfAID, peerKey: formatPeerKey(session.channelType || session.channel, peerId) };
|
|
229
|
+
}
|
|
230
|
+
/** Persist the main-session /fa switch at relation scope (backend independent). */
|
|
231
|
+
export function updateRelationSessionFullAccess(session, config) {
|
|
232
|
+
const selector = mainSessionFullAccessSelector(session);
|
|
233
|
+
if (!selector) {
|
|
234
|
+
throw Object.assign(new Error('fullaccess main session requires a private relation'), { code: 'INVALID_CONTEXT' });
|
|
235
|
+
}
|
|
236
|
+
if (typeof config.enabled !== 'boolean' || !config.authorizedBy.trim()) {
|
|
237
|
+
throw Object.assign(new Error('invalid session fullaccess configuration'), { code: 'INVALID_ARGUMENT' });
|
|
238
|
+
}
|
|
239
|
+
mutateConfig(ConfigTarget.Relation, selector, current => {
|
|
240
|
+
current.sessionFullAccess = { ...config };
|
|
241
|
+
});
|
|
185
242
|
}
|
|
186
243
|
export function createSessionFullAccessAuthorization(input) {
|
|
187
|
-
const config = input.session
|
|
244
|
+
const config = readSessionFullAccessOverride(input.session);
|
|
188
245
|
if (!config?.enabled
|
|
189
246
|
|| input.session.chatType !== 'private'
|
|
190
247
|
|| (input.source !== undefined && input.source !== 'user')
|
|
@@ -209,16 +266,18 @@ export function assertSessionFullAccessAuthorization(authorization, session) {
|
|
|
209
266
|
if (authorization.source !== 'session-policy'
|
|
210
267
|
|| !session
|
|
211
268
|
|| authorization.sessionId !== session.id
|
|
212
|
-
|| !authorization.agentAid
|
|
269
|
+
|| !authorization.agentAid || authorization.agentAid !== session.selfAID
|
|
270
|
+
|| session.chatType !== 'private'
|
|
213
271
|
|| !authorization.policyActor
|
|
214
272
|
|| !hasTrustedPrincipal(authorization.policyActor)) {
|
|
215
273
|
throw new Error('session fullaccess authorization is missing or malformed');
|
|
216
274
|
}
|
|
217
275
|
const current = resolvePrincipal(authorization.agentAid, authorization.policyActor.operatorChannelType, authorization.policyActor.operatorId, authorization.policyActor.operatorChannelKey);
|
|
276
|
+
const config = readSessionFullAccessOverride(session);
|
|
218
277
|
if (!hasTrustedPrincipal({ ...authorization.policyActor, ...current })
|
|
219
278
|
|| current.principalId !== authorization.authorizedBy
|
|
220
|
-
||
|
|
221
|
-
||
|
|
279
|
+
|| config?.enabled !== true
|
|
280
|
+
|| config.authorizedBy !== authorization.authorizedBy
|
|
222
281
|
|| !isAgentFullAccessOwner(authorization.agentAid, authorization.authorizedBy)) {
|
|
223
282
|
throw new Error('session fullaccess authorization is no longer active');
|
|
224
283
|
}
|