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
|
@@ -8,12 +8,13 @@ import { isShellToolName } from '../core/permission/tool-canonical.js';
|
|
|
8
8
|
import { normalizeExecutionPermissionMode, normalizePermissionMode, resolvePhaseOneExecutionSandbox } from '../core/permission/mode.js';
|
|
9
9
|
import { assertWindowsCodexFilesystemRuleBudget, buildCodexProtectedFilesystemRules, compactCodexLinuxFilesystemRules, getExistingRelationAttachmentDirs, isSameOrDescendant, resolveProtectedCandidate, } from '../core/permission/protected-paths.js';
|
|
10
10
|
import { CODEX_THREAD_ACTIVE_WRITER, CodexAppServerClient, } from './codex/app-server-client.js';
|
|
11
|
+
import { getSandboxInitializationFailureCounters, isNestedSandboxInitializationFailure, recordSandboxInitializationFailure, SANDBOX_INITIALIZATION_FAILED, } from '../core/permission/sandbox-runtime.js';
|
|
11
12
|
import { resolveOpenaiConfig, resolveCodexCliPath, resolveCodexPowerShellShimPath, } from './baseagent.js';
|
|
12
13
|
import { logger } from '../utils/logger.js';
|
|
13
14
|
import { resolveProviderService } from '../config/providers.js';
|
|
14
15
|
import { catalogHash } from '../core/model/catalog-service.js';
|
|
15
16
|
import { summarizeToolInputForAudit } from '../utils/tool-summary.js';
|
|
16
|
-
import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
|
|
17
|
+
import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolInfrastructureFailure, auditToolPreflightDenial } from '../core/auth/authorization-audit.js';
|
|
17
18
|
import { classifyError, ErrorType, getToolResultErrorText, isOutputTokenLimitError, isRetryableError } from '../utils/error-utils.js';
|
|
18
19
|
import { findModelSpec, getGatewayPricing as getSharedGatewayPricing } from '../stats/price-resolver.js';
|
|
19
20
|
import { renderActionAsText } from '../core/interaction-router.js';
|
|
@@ -2138,35 +2139,41 @@ export class CodexRunner {
|
|
|
2138
2139
|
const persistentRuntimeEnv = runtimeEnv
|
|
2139
2140
|
? Object.fromEntries(Object.entries(runtimeEnv).filter(([name]) => callMode === 'fullaccess' || name.toUpperCase() !== AGENT_DELEGATION_TOKEN_ENV))
|
|
2140
2141
|
: undefined;
|
|
2141
|
-
let
|
|
2142
|
+
let innerSandboxFallback = false;
|
|
2143
|
+
const canFallbackFromInnerSandbox = process.platform === 'linux'
|
|
2144
|
+
&& executionSandbox.decision.state === 'active';
|
|
2145
|
+
const buildThreadOptions = (fallback = false) => ({
|
|
2142
2146
|
model: callModel,
|
|
2143
2147
|
effort: callEffort,
|
|
2144
2148
|
approvalPolicy: effectiveApprovalPolicy,
|
|
2145
2149
|
approvalsReviewer: 'user',
|
|
2146
|
-
...(
|
|
2147
|
-
|
|
2150
|
+
...(fallback
|
|
2151
|
+
? { sandbox: 'danger-full-access' }
|
|
2152
|
+
: executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
|
|
2153
|
+
config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(fallback ? undefined : executionSandbox.permissionProfileConfig, persistentRuntimeEnv ? { shell_environment_policy: { set: persistentRuntimeEnv } } : undefined, capabilityConfig, userInputConfig, externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionId, threadSessionToken, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined), this.buildLifecycleLockdownConfig(callMode)), callMode, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined),
|
|
2148
2154
|
...(developerInstructions ? { developerInstructions } : {}),
|
|
2149
|
-
};
|
|
2155
|
+
});
|
|
2156
|
+
let threadOptions = buildThreadOptions();
|
|
2150
2157
|
logger.info(`[CodexRunner] runQuery permMode=${requestedPermissionMode}->${callMode} ` +
|
|
2151
2158
|
`role=${executionSandbox.decision.role ?? 'none'} sandbox=${executionSandbox.decision.state}`);
|
|
2152
2159
|
let threadResponse;
|
|
2153
2160
|
let previousAppServer;
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
catch (error) {
|
|
2162
|
-
if (isCodexActiveWriterError(error) && previousAppServer && previousAppServer !== appServer) {
|
|
2163
|
-
// Some Codex builds acknowledge unsubscribe before unloading the
|
|
2164
|
-
// runtime. Archive/unarchive is a synchronous per-thread teardown
|
|
2165
|
-
// and preserves the same persisted thread id for the retry.
|
|
2166
|
-
await this.archiveThreadForHandoff(previousAppServer, appServer, agentSessionId);
|
|
2167
|
-
threadResponse = await appServer.threadResume(agentSessionId, projectPath, threadOptions);
|
|
2161
|
+
const openThread = async () => {
|
|
2162
|
+
if (agentSessionId) {
|
|
2163
|
+
// A thread may have been loaded by the other permission-mode client.
|
|
2164
|
+
// Release that one thread before asking this client to resume it.
|
|
2165
|
+
previousAppServer = await this.prepareThreadSubscription(appServer, agentSessionId);
|
|
2166
|
+
try {
|
|
2167
|
+
return await this.resumeThreadAllowingWriterRelease(appServer, agentSessionId, projectPath, threadOptions, previousAppServer);
|
|
2168
2168
|
}
|
|
2169
|
-
|
|
2169
|
+
catch (error) {
|
|
2170
|
+
if (isCodexActiveWriterError(error) && previousAppServer && previousAppServer !== appServer) {
|
|
2171
|
+
// Some Codex builds acknowledge unsubscribe before unloading the
|
|
2172
|
+
// runtime. Archive/unarchive is a synchronous per-thread teardown
|
|
2173
|
+
// and preserves the same persisted thread id for the retry.
|
|
2174
|
+
await this.archiveThreadForHandoff(previousAppServer, appServer, agentSessionId);
|
|
2175
|
+
return appServer.threadResume(agentSessionId, projectPath, threadOptions);
|
|
2176
|
+
}
|
|
2170
2177
|
// A legacy main session can retain a provider ID after its rollout was
|
|
2171
2178
|
// removed externally. It is safe to recover before input submission;
|
|
2172
2179
|
// topic bindings remain authoritative and fail closed.
|
|
@@ -2198,17 +2205,64 @@ export class CodexRunner {
|
|
|
2198
2205
|
agentSessionId = undefined;
|
|
2199
2206
|
resumingThread = false;
|
|
2200
2207
|
threadSessionToken = this.createThreadCredential();
|
|
2201
|
-
threadOptions =
|
|
2202
|
-
...threadOptions,
|
|
2203
|
-
config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, persistentRuntimeEnv ? { shell_environment_policy: { set: persistentRuntimeEnv } } : undefined, capabilityConfig, userInputConfig, externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionId, threadSessionToken, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined), this.buildLifecycleLockdownConfig(callMode)), callMode, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined),
|
|
2204
|
-
};
|
|
2208
|
+
threadOptions = buildThreadOptions(innerSandboxFallback);
|
|
2205
2209
|
logger.warn(`[CodexRunner] recovered missing rollout before input submission: session=${sessionId} thread=${missingThreadId}`);
|
|
2206
|
-
|
|
2210
|
+
return appServer.threadStart(projectPath, threadOptions);
|
|
2207
2211
|
}
|
|
2208
2212
|
}
|
|
2213
|
+
return appServer.threadStart(projectPath, threadOptions);
|
|
2214
|
+
};
|
|
2215
|
+
try {
|
|
2216
|
+
threadResponse = await openThread();
|
|
2209
2217
|
}
|
|
2210
|
-
|
|
2211
|
-
|
|
2218
|
+
catch (error) {
|
|
2219
|
+
if (!canFallbackFromInnerSandbox || !isNestedSandboxInitializationFailure(error))
|
|
2220
|
+
throw error;
|
|
2221
|
+
innerSandboxFallback = true;
|
|
2222
|
+
const circuit = recordSandboxInitializationFailure(error, [], Date.now(), sessionId);
|
|
2223
|
+
const context = this.permissionContexts.get(sessionId);
|
|
2224
|
+
const fallbackRequestId = modelOverride?.turn?.inputId ?? `codex-sandbox-fallback-${Date.now()}`;
|
|
2225
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
2226
|
+
auditToolInfrastructureFailure({
|
|
2227
|
+
toolName: 'Bash',
|
|
2228
|
+
policyCode: SANDBOX_INITIALIZATION_FAILED,
|
|
2229
|
+
reason: detail.slice(0, 512),
|
|
2230
|
+
sessionId,
|
|
2231
|
+
agentAid: context?.selfAid,
|
|
2232
|
+
agentName: context?.agentName,
|
|
2233
|
+
permissionMode: callMode,
|
|
2234
|
+
role: context?.role,
|
|
2235
|
+
callId: fallbackRequestId,
|
|
2236
|
+
taskId: context?.taskId,
|
|
2237
|
+
occurrences: circuit.occurrences,
|
|
2238
|
+
fallback: true,
|
|
2239
|
+
sandboxFailure: {
|
|
2240
|
+
kind: circuit.kind,
|
|
2241
|
+
observation: 'fallback',
|
|
2242
|
+
counters: getSandboxInitializationFailureCounters(),
|
|
2243
|
+
},
|
|
2244
|
+
});
|
|
2245
|
+
await context?.recordExecutionAnomaly?.({
|
|
2246
|
+
code: 'capability_unavailable',
|
|
2247
|
+
severity: 'warning',
|
|
2248
|
+
phase: 'execution',
|
|
2249
|
+
occurredAt: Date.now(),
|
|
2250
|
+
correlationId: fallbackRequestId,
|
|
2251
|
+
requestId: fallbackRequestId,
|
|
2252
|
+
sessionId,
|
|
2253
|
+
toolName: 'Bash',
|
|
2254
|
+
policyCode: SANDBOX_INITIALIZATION_FAILED,
|
|
2255
|
+
decisionSource: 'infrastructure',
|
|
2256
|
+
agentAid: context?.selfAid,
|
|
2257
|
+
agentName: context?.agentName,
|
|
2258
|
+
permissionMode: callMode,
|
|
2259
|
+
summary: `Codex inner sandbox unavailable; retrying with outer EvolCore guard: ${detail}`.slice(0, 512),
|
|
2260
|
+
effect: 'fallback_used',
|
|
2261
|
+
});
|
|
2262
|
+
logger.warn(`[CodexSandbox] inner sandbox initialization failed; retrying with outer H-class guard ` +
|
|
2263
|
+
`session=${sessionId} occurrences=${circuit.occurrences}: ${detail}`);
|
|
2264
|
+
threadOptions = buildThreadOptions(true);
|
|
2265
|
+
threadResponse = await openThread();
|
|
2212
2266
|
}
|
|
2213
2267
|
let threadId = threadResponse.thread?.id || agentSessionId;
|
|
2214
2268
|
if (!threadId)
|
|
@@ -2401,7 +2455,9 @@ export class CodexRunner {
|
|
|
2401
2455
|
model: callModel,
|
|
2402
2456
|
effort: callEffort,
|
|
2403
2457
|
approvalPolicy: effectiveApprovalPolicy,
|
|
2404
|
-
...(
|
|
2458
|
+
...(innerSandboxFallback
|
|
2459
|
+
? { sandbox: 'danger-full-access' }
|
|
2460
|
+
: executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
|
|
2405
2461
|
});
|
|
2406
2462
|
if (!resumingThread) {
|
|
2407
2463
|
let confirmationInFlight;
|
|
@@ -805,7 +805,7 @@ export class EcagentRunner {
|
|
|
805
805
|
const providerId = providerOverride ?? this.config.providerId;
|
|
806
806
|
if (!providerId)
|
|
807
807
|
return this.config;
|
|
808
|
-
const provider = resolveProviderServiceForBaseagent(providerId, 'ecagent'
|
|
808
|
+
const provider = resolveProviderServiceForBaseagent(providerId, 'ecagent');
|
|
809
809
|
if (provider.style !== 'openai-compatible') {
|
|
810
810
|
throw new Error(`Provider ${providerId} uses unsupported ecagent style: ${provider.style}`);
|
|
811
811
|
}
|
|
@@ -369,7 +369,7 @@ export class GeminiRunner {
|
|
|
369
369
|
}
|
|
370
370
|
currentProviderConfig(providerOverride) {
|
|
371
371
|
const config = this.agentAid
|
|
372
|
-
? { agents: { gemini: resolveEffective({ self: this.agentAid }, { cache: true
|
|
372
|
+
? { agents: { gemini: resolveEffective({ self: this.agentAid }, { cache: true }).baseagents?.gemini ?? this.config.agents?.gemini } }
|
|
373
373
|
: this.config;
|
|
374
374
|
return resolveGoogleConfig(config, providerOverride ? { provider: providerOverride } : undefined);
|
|
375
375
|
}
|
|
@@ -56,6 +56,45 @@ export async function readPersonalFsBytesWithinBudget(client, path, maxBytes, op
|
|
|
56
56
|
throw new FsReadBudgetError(maxBytes);
|
|
57
57
|
return bytes;
|
|
58
58
|
}
|
|
59
|
+
export class AuthoritativeFsReadError extends Error {
|
|
60
|
+
code;
|
|
61
|
+
constructor(code, message) {
|
|
62
|
+
super(message);
|
|
63
|
+
this.code = code;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Full authenticated RPC read for private ACLs; never requests an HTTP ticket. */
|
|
67
|
+
export async function readAuthoritativePersonalFsObject(client, path, owner, maxBytes) {
|
|
68
|
+
validateFsReadBudget(maxBytes);
|
|
69
|
+
if (!path.startsWith('/') || path.endsWith('/') || path.includes('\\') ||
|
|
70
|
+
/[\u0000-\u001f\u007f]/.test(path) || path.slice(1).split('/').some(p => !p || p === '.' || p === '..')) {
|
|
71
|
+
throw new AuthoritativeFsReadError('INVALID_PATH', 'authoritative cat requires a canonical absolute object path');
|
|
72
|
+
}
|
|
73
|
+
const key = path.slice(1);
|
|
74
|
+
const value = await client.call('storage.get_object', {
|
|
75
|
+
owner_aid: owner, bucket: 'default', object_key: key, consistency: 'authoritative',
|
|
76
|
+
});
|
|
77
|
+
if (!isRecord(value) || value.owner_aid !== owner || value.bucket !== 'default' ||
|
|
78
|
+
(value.object_key ?? (typeof value.path === 'string' ? value.path.replace(/^\//, '') : undefined)) !== key) {
|
|
79
|
+
throw new AuthoritativeFsReadError('FS_INVALID_OBJECT', 'authoritative response identity/path mismatch');
|
|
80
|
+
}
|
|
81
|
+
if (value.exists === false)
|
|
82
|
+
throw new AuthoritativeFsReadError('FS_NOT_FOUND', 'authoritative object is absent or inaccessible');
|
|
83
|
+
if (value.exists !== true || !Number.isSafeInteger(value.version) || value.version < 1 ||
|
|
84
|
+
!Number.isSafeInteger(value.size_bytes) || value.size_bytes < 0 || typeof value.content !== 'string' ||
|
|
85
|
+
typeof value.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(value.sha256)) {
|
|
86
|
+
throw new AuthoritativeFsReadError('FS_INVALID_OBJECT', 'authoritative response metadata is incomplete');
|
|
87
|
+
}
|
|
88
|
+
if (value.size_bytes > maxBytes || value.content.length > 4 * Math.ceil(maxBytes / 3)) {
|
|
89
|
+
throw new FsReadBudgetError(maxBytes);
|
|
90
|
+
}
|
|
91
|
+
const bytes = Buffer.from(value.content, 'base64');
|
|
92
|
+
if (bytes.toString('base64') !== value.content || bytes.length !== value.size_bytes || sha256Hex(bytes) !== value.sha256) {
|
|
93
|
+
throw new AuthoritativeFsReadError('FS_INVALID_OBJECT', 'authoritative content encoding, size or hash mismatch');
|
|
94
|
+
}
|
|
95
|
+
const { content: _content, ...metadata } = value;
|
|
96
|
+
return { bytes, metadata };
|
|
97
|
+
}
|
|
59
98
|
export class GroupFsDownloadError extends Error {
|
|
60
99
|
code;
|
|
61
100
|
constructor(code, message) {
|
|
@@ -1,5 +1,41 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
import { fileURLToPath } from 'node:url';
|
|
3
|
+
/** Resolve a peer kind from authoritative evidence; AID spelling is never evidence. */
|
|
4
|
+
export function resolveAunTargetKind(evidence) {
|
|
5
|
+
const candidates = [];
|
|
6
|
+
const sources = [];
|
|
7
|
+
for (const [source, kind] of [['route', evidence.routeKind], ['relation', evidence.targetKind]]) {
|
|
8
|
+
if (kind === undefined)
|
|
9
|
+
continue;
|
|
10
|
+
if (kind !== 'private' && kind !== 'group')
|
|
11
|
+
return { kind: 'unknown', reason: 'invalid', sources };
|
|
12
|
+
candidates.push(kind);
|
|
13
|
+
sources.push(source);
|
|
14
|
+
}
|
|
15
|
+
if (evidence.verifiedType !== undefined) {
|
|
16
|
+
if (typeof evidence.verifiedType !== 'string' || !evidence.verifiedType.trim()) {
|
|
17
|
+
return { kind: 'unknown', reason: 'invalid', sources };
|
|
18
|
+
}
|
|
19
|
+
if (evidence.verifiedType.trim().toLowerCase() === 'unknown') {
|
|
20
|
+
return { kind: 'unknown', reason: 'invalid', sources };
|
|
21
|
+
}
|
|
22
|
+
candidates.push(evidence.verifiedType.trim().toLowerCase() === 'group' ? 'group' : 'private');
|
|
23
|
+
sources.push('agentmd');
|
|
24
|
+
}
|
|
25
|
+
if (!candidates.length)
|
|
26
|
+
return { kind: 'unknown', reason: 'missing', sources };
|
|
27
|
+
if (candidates.some(kind => kind !== candidates[0]))
|
|
28
|
+
return { kind: 'unknown', reason: 'conflict', sources };
|
|
29
|
+
return { kind: candidates[0], reason: 'resolved', sources };
|
|
30
|
+
}
|
|
31
|
+
/** Accept cached type evidence only after signature verification for this exact AID. */
|
|
32
|
+
export function verifiedPeerType(targetAid, identity) {
|
|
33
|
+
if (identity?.aid !== targetAid || identity.source !== 'agentmd'
|
|
34
|
+
|| !Number.isFinite(identity.verifiedAt) || !(identity.verifiedAt > 0) || identity.lastCheckedAt === 0) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
return typeof identity.type === 'string' && identity.type.trim() ? identity.type.trim() : undefined;
|
|
38
|
+
}
|
|
3
39
|
const requireSdk = createRequire(import.meta.url);
|
|
4
40
|
let groupValidator;
|
|
5
41
|
/** Validate a group command argument, expanding a local base to a full AID. */
|
|
@@ -28,24 +64,3 @@ export function sameGroupAid(left, right) {
|
|
|
28
64
|
return false;
|
|
29
65
|
}
|
|
30
66
|
}
|
|
31
|
-
/**
|
|
32
|
-
* Legacy group identity hint, NOT a format validator. Canonical group AIDs and
|
|
33
|
-
* private AIDs share a syntax; prefer trusted chat/targetKind information.
|
|
34
|
-
* Do not broaden this predicate to every SDK-valid group argument.
|
|
35
|
-
*/
|
|
36
|
-
export function isExplicitGroupId(value) {
|
|
37
|
-
const id = value.trim();
|
|
38
|
-
if (!id)
|
|
39
|
-
return false;
|
|
40
|
-
return /^\d+\.[a-z0-9.-]+$/i.test(id)
|
|
41
|
-
|| /^grp_[a-z0-9_-]+$/i.test(id)
|
|
42
|
-
|| /^g-[a-z0-9_-]+(?:[.@][a-z0-9.-]+)?$/i.test(id);
|
|
43
|
-
}
|
|
44
|
-
/** Legacy named-group hint for generic relation data without authoritative type metadata. */
|
|
45
|
-
export function isLegacyNamedGroupIdHint(value) {
|
|
46
|
-
const id = value.trim();
|
|
47
|
-
if (!id)
|
|
48
|
-
return false;
|
|
49
|
-
return /^grp_[a-z0-9_-]+$/i.test(id)
|
|
50
|
-
|| /^g-[a-z0-9_-]+(?:[.@][a-z0-9.-]+)?$/i.test(id);
|
|
51
|
-
}
|
|
@@ -63,6 +63,11 @@ export function applyGroupRoutingPayloadFields(payload, args, runtimeContext) {
|
|
|
63
63
|
payload.thread_id = threadId;
|
|
64
64
|
else if (payload.thread_id !== undefined)
|
|
65
65
|
delete payload.thread_id;
|
|
66
|
+
// Mark the final user-visible text message so the wire ext carries isFinal.
|
|
67
|
+
// buildWireExt (daemon side) merges this into the outgoing ext dictionary.
|
|
68
|
+
if (payload.type === 'text') {
|
|
69
|
+
payload.ext = { isFinal: true, ...(payload.ext && typeof payload.ext === 'object' && !Array.isArray(payload.ext) ? payload.ext : {}) };
|
|
70
|
+
}
|
|
66
71
|
}
|
|
67
72
|
function groupSendLogMetadata(args, payload, runtimeContext) {
|
|
68
73
|
const classified = payload ? classifyAunPayloadForLog(payload) : undefined;
|
|
@@ -9,7 +9,7 @@ import { isValidAid } from '../aid/validation.js';
|
|
|
9
9
|
import { tryParseChannelKey } from '../../core/channel-loader.js';
|
|
10
10
|
import { normalizeThreadOptionValue } from '../../core/thread/topic-id.js';
|
|
11
11
|
import { parseTimeArg, TIME_ARG_FORMATS } from '../../cli/cli-argv.js';
|
|
12
|
-
import { DEFAULT_FS_CAT_BYTES, MAX_FS_CAT_BYTES, FsReadBudgetError, downloadGroupFsBytes, readPersonalFsBytesWithinBudget, } from '../group/fs-download.js';
|
|
12
|
+
import { DEFAULT_FS_CAT_BYTES, MAX_FS_CAT_BYTES, FsReadBudgetError, downloadGroupFsBytes, readPersonalFsBytesWithinBudget, readAuthoritativePersonalFsObject, AuthoritativeFsReadError, } from '../group/fs-download.js';
|
|
13
13
|
import { groupBan, groupBanlist, groupBlock, groupUnblock, groupBlocklist, groupReportStatus, groupMemberStatuses, groupCreate, groupDissolve, groupInfo, groupInvite, groupJoin, groupKick, groupLeave, groupList, groupMembers, groupOnline, groupPull, groupAck, groupAcceptInvite, groupInvites, groupRejectInvite, groupRevokeInvite, groupResume, groupRules, groupRulesFileGet, groupRulesFilePublish, groupRulesFileSet, groupSetRole, groupSuspend, groupTransferOwner, groupUnban, groupUpdate, groupUpdateRules, } from '../group/operations.js';
|
|
14
14
|
import { handleGroupMenu, GroupMenuError } from '../../core/command/group-menu.js';
|
|
15
15
|
import { readRolesConfig } from '../../config/roles.js';
|
|
@@ -803,9 +803,9 @@ export class ManagedFsOperationError extends Error {
|
|
|
803
803
|
}
|
|
804
804
|
const FS_VALUE_FLAGS = new Set([
|
|
805
805
|
'--as', '--format', '--max-bytes', '--head-bytes', '--name', '--pattern', '--type', '--node-type',
|
|
806
|
-
'--size', '--mtime', '--page', '--page-size', '-m', '-x',
|
|
806
|
+
'--size', '--mtime', '--page', '--page-size', '-m', '-x', '--expires',
|
|
807
807
|
]);
|
|
808
|
-
const FS_BOOLEAN_FLAGS = new Set(['-p', '--parents', '-r', '--recursive', '-f', '--force', '--overwrite']);
|
|
808
|
+
const FS_BOOLEAN_FLAGS = new Set(['-p', '--parents', '-r', '--recursive', '-f', '--force', '--overwrite', '--authoritative']);
|
|
809
809
|
function failFs(code, reason) {
|
|
810
810
|
return { ok: false, code, reason };
|
|
811
811
|
}
|
|
@@ -820,6 +820,26 @@ function positiveInteger(value, flag, max) {
|
|
|
820
820
|
}
|
|
821
821
|
return number;
|
|
822
822
|
}
|
|
823
|
+
const MAX_MANAGED_LINK_SECONDS = 7 * 24 * 3600;
|
|
824
|
+
/** Parse --expires: bare seconds, or a duration such as 30m / 12h / 7d; 0 means no expiry. */
|
|
825
|
+
function parseManagedLinkExpiry(value) {
|
|
826
|
+
if (value === undefined)
|
|
827
|
+
return undefined;
|
|
828
|
+
const text = value.trim().toLowerCase();
|
|
829
|
+
if (!text)
|
|
830
|
+
return failFs('INVALID_ARGUMENT', '--expires requires a duration');
|
|
831
|
+
const match = /^(\d+)([smhd])?$/.exec(text);
|
|
832
|
+
if (!match)
|
|
833
|
+
return failFs('INVALID_ARGUMENT', '--expires accepts seconds, 30m, 12h, 7d, or 0 for a non-expiring link');
|
|
834
|
+
const unit = match[2] === undefined
|
|
835
|
+
? 1
|
|
836
|
+
: { s: 1, m: 60, h: 3600, d: 86400 }[match[2]];
|
|
837
|
+
const seconds = Number(match[1]) * unit;
|
|
838
|
+
if (!Number.isSafeInteger(seconds) || seconds < 0 || seconds > MAX_MANAGED_LINK_SECONDS) {
|
|
839
|
+
return failFs('INVALID_ARGUMENT', `--expires must be between 0 and ${MAX_MANAGED_LINK_SECONDS} seconds`);
|
|
840
|
+
}
|
|
841
|
+
return seconds;
|
|
842
|
+
}
|
|
823
843
|
function parseRemote(value, allowEmpty) {
|
|
824
844
|
if (!value)
|
|
825
845
|
return failFs('INVALID_ARGUMENT', 'missing remote storage path');
|
|
@@ -849,7 +869,7 @@ function parseRemote(value, allowEmpty) {
|
|
|
849
869
|
export function resolveManagedFsOperation(argv) {
|
|
850
870
|
const raw = argv[0] === 'fs' ? argv.slice(1) : argv;
|
|
851
871
|
const rawKind = raw[0];
|
|
852
|
-
if (!rawKind || !['ls', 'stat', 'lstat', 'cat', 'find', 'df', 'getfacl', 'setfacl', 'mkdir', 'cp', 'mv', 'rm'].includes(rawKind)) {
|
|
872
|
+
if (!rawKind || !['ls', 'stat', 'lstat', 'cat', 'find', 'df', 'getfacl', 'setfacl', 'mkdir', 'cp', 'mv', 'rm', 'link'].includes(rawKind)) {
|
|
853
873
|
return failFs('NOT_ALLOWED', `unsupported managed fs command: ${rawKind || '<missing>'}`);
|
|
854
874
|
}
|
|
855
875
|
const values = new Map();
|
|
@@ -903,9 +923,10 @@ export function resolveManagedFsOperation(argv) {
|
|
|
903
923
|
df: new Set(['--as', '--format']), mkdir: new Set(['--as', '--format']), cp: new Set(['--as', '--format']),
|
|
904
924
|
mv: new Set(['--as', '--format']), rm: new Set(['--as', '--format']),
|
|
905
925
|
getfacl: new Set(['--as', '--format']), setfacl: new Set(['--as', '--format', '-m', '-x']),
|
|
926
|
+
link: new Set(['--as', '--format', '--expires']),
|
|
906
927
|
};
|
|
907
928
|
const allowedBoolean = {
|
|
908
|
-
ls: new Set(), stat: new Set(), lstat: new Set(), cat: new Set(), find: new Set(), df: new Set(), getfacl: new Set(), setfacl: new Set(),
|
|
929
|
+
ls: new Set(), stat: new Set(), lstat: new Set(), cat: new Set(['--authoritative']), find: new Set(), df: new Set(), getfacl: new Set(), setfacl: new Set(), link: new Set(),
|
|
909
930
|
mkdir: new Set(['-p', '--parents']), cp: new Set(['-r', '--recursive', '-f', '--force', '--overwrite']),
|
|
910
931
|
mv: new Set(['-f', '--force', '--overwrite']), rm: new Set(['-r', '--recursive', '-f', '--force', '--overwrite']),
|
|
911
932
|
};
|
|
@@ -986,6 +1007,20 @@ export function resolveManagedFsOperation(argv) {
|
|
|
986
1007
|
const remote = remoteOrError(positionals[0], rawKind === 'df');
|
|
987
1008
|
if (!('targetAid' in remote))
|
|
988
1009
|
return remote;
|
|
1010
|
+
if (rawKind === 'link') {
|
|
1011
|
+
if (remote.remotePath === '/' || remote.remotePath === '') {
|
|
1012
|
+
return failFs('INVALID_PATH', 'managed link requires a file path, not the storage root');
|
|
1013
|
+
}
|
|
1014
|
+
const expires = parseManagedLinkExpiry(values.get('--expires'));
|
|
1015
|
+
if (expires !== undefined && typeof expires === 'object')
|
|
1016
|
+
return expires;
|
|
1017
|
+
return { ok: true, command: {
|
|
1018
|
+
kind: 'link', operationId: 'ec.fs.link',
|
|
1019
|
+
canonicalArgv: ['fs', 'link', positionals[0], ...(expires !== undefined ? ['--expires', String(expires)] : []), ...(actorAid ? ['--as', actorAid] : [])],
|
|
1020
|
+
actorAid, targetAid: remote.targetAid, remotePath: remote.remotePath,
|
|
1021
|
+
...(expires !== undefined ? { expiresSeconds: expires } : {}),
|
|
1022
|
+
} };
|
|
1023
|
+
}
|
|
989
1024
|
if (rawKind === 'mkdir')
|
|
990
1025
|
return { ok: true, command: {
|
|
991
1026
|
kind: 'mkdir', operationId: 'ec.fs.mkdir', canonicalArgv: ['fs', 'mkdir', positionals[0], ...(actorAid ? ['--as', actorAid] : [])],
|
|
@@ -1015,8 +1050,9 @@ export function resolveManagedFsOperation(argv) {
|
|
|
1015
1050
|
if (nodeType !== undefined && !['f', 'd', 'l'].includes(nodeType))
|
|
1016
1051
|
return failFs('INVALID_ARGUMENT', '--type only supports f|d|l');
|
|
1017
1052
|
return { ok: true, command: {
|
|
1018
|
-
kind: effectiveKind, operationId: `ec.fs.${effectiveKind}`, canonicalArgv: ['fs', effectiveKind, positionals[0], ...(actorAid ? ['--as', actorAid] : [])],
|
|
1053
|
+
kind: effectiveKind, operationId: `ec.fs.${effectiveKind}`, canonicalArgv: ['fs', effectiveKind, positionals[0], ...(actorAid ? ['--as', actorAid] : []), ...(booleanFlags.has('--authoritative') ? ['--authoritative'] : [])],
|
|
1019
1054
|
actorAid, targetAid: remote.targetAid, remotePath: remote.remotePath, maxBytes, headBytes,
|
|
1055
|
+
authoritative: booleanFlags.has('--authoritative'),
|
|
1020
1056
|
name: values.get('--name') ?? values.get('--pattern'), nodeType, size: values.get('--size'), mtime: values.get('--mtime'), page, pageSize,
|
|
1021
1057
|
} };
|
|
1022
1058
|
}
|
|
@@ -1076,6 +1112,9 @@ export async function executeManagedFsOperationWithClient(command, client) {
|
|
|
1076
1112
|
if (!command.storageBackend)
|
|
1077
1113
|
throw new ManagedFsOperationError('INVALID_TARGET', 'managed fs storage backend must be resolved before execution');
|
|
1078
1114
|
const ref = `${command.targetAid}:${command.remotePath}`;
|
|
1115
|
+
if (command.authoritative && (command.kind !== 'cat' || command.storageBackend !== 'personal')) {
|
|
1116
|
+
throw new ManagedFsOperationError('NOT_ALLOWED', 'authoritative reads require personal storage cat');
|
|
1117
|
+
}
|
|
1079
1118
|
try {
|
|
1080
1119
|
return await (async () => {
|
|
1081
1120
|
if (command.storageBackend === 'personal') {
|
|
@@ -1126,12 +1165,30 @@ export async function executeManagedFsOperationWithClient(command, client) {
|
|
|
1126
1165
|
}) };
|
|
1127
1166
|
case 'df':
|
|
1128
1167
|
return { ok: true, command: 'df', path: `${owner}:`, usage: await client.storage.df({ owner }) };
|
|
1168
|
+
case 'link': {
|
|
1169
|
+
// The SDK wrapper fixes the ticket lifetime, so call the RPC directly to honor --expires.
|
|
1170
|
+
const ticket = await client.call('storage.create_download_ticket', {
|
|
1171
|
+
owner_aid: owner,
|
|
1172
|
+
bucket: 'default',
|
|
1173
|
+
object_key: command.remotePath.replace(/^\/+/, ''),
|
|
1174
|
+
...(command.expiresSeconds !== undefined ? { expire_in_seconds: command.expiresSeconds } : {}),
|
|
1175
|
+
});
|
|
1176
|
+
const record = (ticket && typeof ticket === 'object' ? ticket : {});
|
|
1177
|
+
const url = typeof record.download_url === 'string' && record.download_url
|
|
1178
|
+
? record.download_url
|
|
1179
|
+
: typeof record.url === 'string' ? record.url : '';
|
|
1180
|
+
if (!url)
|
|
1181
|
+
throw new ManagedFsOperationError('DEPENDENCY_UNAVAILABLE', 'storage did not return a download url');
|
|
1182
|
+
return { ok: true, command: 'link', path: ref, url, expireAt: record.expire_at ?? null };
|
|
1183
|
+
}
|
|
1129
1184
|
case 'getfacl':
|
|
1130
1185
|
return { ok: true, command: 'getfacl', path: ref, result: await client.storage.listAcl(command.remotePath, { owner }) };
|
|
1131
1186
|
case 'setfacl':
|
|
1132
1187
|
throw new ManagedFsOperationError('NOT_ALLOWED', 'Managed personal storage ACL changes are not supported');
|
|
1133
1188
|
case 'cat': {
|
|
1134
|
-
const bytes =
|
|
1189
|
+
const bytes = command.authoritative
|
|
1190
|
+
? (await readAuthoritativePersonalFsObject(client, command.remotePath, owner, command.maxBytes ?? DEFAULT_FS_CAT_BYTES)).bytes
|
|
1191
|
+
: await readPersonalFsBytesWithinBudget(client, command.remotePath, command.maxBytes ?? DEFAULT_FS_CAT_BYTES, { owner });
|
|
1135
1192
|
const headBytes = Math.min(command.headBytes ?? 256, MAX_MANAGED_FS_HEAD_BYTES, bytes.byteLength);
|
|
1136
1193
|
if (bytes.subarray(0, Math.min(bytes.byteLength, 8192)).some(byte => byte === 0)) {
|
|
1137
1194
|
return {
|
|
@@ -1206,6 +1263,8 @@ export async function executeManagedFsOperationWithClient(command, client) {
|
|
|
1206
1263
|
}
|
|
1207
1264
|
case 'df':
|
|
1208
1265
|
return { ok: true, command: 'df', path: `${command.targetAid}:`, usage: await client.group.fs.df(`${command.targetAid}:`) };
|
|
1266
|
+
case 'link':
|
|
1267
|
+
throw new ManagedFsOperationError('NOT_ALLOWED', 'managed link is only supported for personal storage');
|
|
1209
1268
|
case 'getfacl':
|
|
1210
1269
|
return { ok: true, command: 'getfacl', path: ref, result: await client.group.fs.getAcl(ref) };
|
|
1211
1270
|
case 'setfacl': {
|
|
@@ -1248,6 +1307,8 @@ export async function executeManagedFsOperationWithClient(command, client) {
|
|
|
1248
1307
|
throw error;
|
|
1249
1308
|
if (error instanceof FsReadBudgetError)
|
|
1250
1309
|
throw new ManagedFsOperationError(error.code, error.message);
|
|
1310
|
+
if (error instanceof AuthoritativeFsReadError)
|
|
1311
|
+
throw new ManagedFsOperationError(error.code, error.message);
|
|
1251
1312
|
throw new ManagedFsOperationError('FS_OPERATION_FAILED', error instanceof Error ? error.message : String(error));
|
|
1252
1313
|
}
|
|
1253
1314
|
}
|
package/dist/aun/msg/p2p.js
CHANGED
|
@@ -82,6 +82,11 @@ function applyRoutingPayloadFields(payload, args, runtimeContext, includeRuntime
|
|
|
82
82
|
const refMessageId = runtimeRefMessageIdForMsgSend({ from: args.from, runtime: runtimeContext });
|
|
83
83
|
if (refMessageId && !payload.ref_message_id)
|
|
84
84
|
payload.ref_message_id = refMessageId;
|
|
85
|
+
// Mark the final user-visible text message so the wire ext carries isFinal.
|
|
86
|
+
// buildWireExt (daemon side) merges this into the outgoing ext dictionary.
|
|
87
|
+
if (payload.type === 'text') {
|
|
88
|
+
payload.ext = { isFinal: true, ...(payload.ext && typeof payload.ext === 'object' && !Array.isArray(payload.ext) ? payload.ext : {}) };
|
|
89
|
+
}
|
|
85
90
|
}
|
|
86
91
|
function msgSendThreadId(args, payload, runtimeContext) {
|
|
87
92
|
const payloadThreadId = typeof payload?.thread_id === 'string' && payload.thread_id.trim()
|
|
@@ -19,6 +19,8 @@ import path from 'path';
|
|
|
19
19
|
import { ServiceProxyClient, EndpointPolicy } from '@agentunion/fastaun';
|
|
20
20
|
import { resolvePaths } from '../paths.js';
|
|
21
21
|
import { logger } from '../utils/logger.js';
|
|
22
|
+
import { parseEcwebInstanceRecord } from '../contracts/ecweb-instance.js';
|
|
23
|
+
import { getProcessStartTime, startTimeMatches } from '../utils/process-introspect.js';
|
|
22
24
|
const LOG = '[ServiceProxy]';
|
|
23
25
|
const INSTANCE_DISCOVERY_TIMEOUT_MS = 10_000;
|
|
24
26
|
const INSTANCE_DISCOVERY_INTERVAL_MS = 250;
|
|
@@ -29,7 +31,7 @@ function sleep(ms) {
|
|
|
29
31
|
* 读 data/instance/ 下指定服务的存活实例端口。
|
|
30
32
|
* 取 startedAt 最新的一条(多实例保护下通常只有一条存活)。
|
|
31
33
|
*/
|
|
32
|
-
function discoverInstancePort(serviceName) {
|
|
34
|
+
function discoverInstancePort(serviceName, expectedPort) {
|
|
33
35
|
const dir = resolvePaths().instanceDir;
|
|
34
36
|
let files;
|
|
35
37
|
try {
|
|
@@ -47,7 +49,10 @@ function discoverInstancePort(serviceName) {
|
|
|
47
49
|
continue;
|
|
48
50
|
const filePid = Number(match[1]);
|
|
49
51
|
try {
|
|
50
|
-
const
|
|
52
|
+
const raw = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf-8'));
|
|
53
|
+
const rec = serviceName === 'ecweb'
|
|
54
|
+
? parseEcwebInstanceRecord(raw, resolvePaths().root, file)
|
|
55
|
+
: raw;
|
|
51
56
|
if (rec
|
|
52
57
|
&& Number.isInteger(rec.pid)
|
|
53
58
|
&& rec.pid > 0
|
|
@@ -55,11 +60,13 @@ function discoverInstancePort(serviceName) {
|
|
|
55
60
|
&& isProcessAlive(rec.pid)
|
|
56
61
|
&& typeof rec.startedAt === 'number'
|
|
57
62
|
&& Number.isFinite(rec.startedAt)
|
|
63
|
+
&& (serviceName !== 'ecweb' || !('schemaVersion' in rec) || startTimeMatches(rec.startedAt, getProcessStartTime(rec.pid)))
|
|
58
64
|
&& rec.startedAt >= 0
|
|
59
65
|
&& Number.isInteger(rec.port)
|
|
60
66
|
&& rec.port >= 1
|
|
61
|
-
&& rec.port <= 65535
|
|
62
|
-
|
|
67
|
+
&& rec.port <= 65535
|
|
68
|
+
&& (expectedPort === undefined || rec.port === expectedPort)) {
|
|
69
|
+
records.push({ pid: rec.pid, port: rec.port, startedAt: rec.startedAt });
|
|
63
70
|
}
|
|
64
71
|
}
|
|
65
72
|
catch {
|
|
@@ -81,11 +88,11 @@ function isProcessAlive(pid) {
|
|
|
81
88
|
return e?.code === 'EPERM';
|
|
82
89
|
}
|
|
83
90
|
}
|
|
84
|
-
async function waitForInstancePort(serviceName) {
|
|
91
|
+
async function waitForInstancePort(serviceName, expectedPort) {
|
|
85
92
|
const deadline = Date.now() + INSTANCE_DISCOVERY_TIMEOUT_MS;
|
|
86
93
|
let loggedWait = false;
|
|
87
94
|
while (Date.now() <= deadline) {
|
|
88
|
-
const port = discoverInstancePort(serviceName);
|
|
95
|
+
const port = discoverInstancePort(serviceName, expectedPort);
|
|
89
96
|
if (port)
|
|
90
97
|
return port;
|
|
91
98
|
if (!loggedWait) {
|
|
@@ -101,7 +108,7 @@ async function waitForInstancePort(serviceName) {
|
|
|
101
108
|
*/
|
|
102
109
|
async function resolveEndpoint(svc) {
|
|
103
110
|
if (svc.proxy?.source === 'instance') {
|
|
104
|
-
const port = await waitForInstancePort(svc.name);
|
|
111
|
+
const port = await waitForInstancePort(svc.name, svc.port);
|
|
105
112
|
if (!port) {
|
|
106
113
|
logger.warn(`${LOG} 服务 "${svc.name}" source=instance 等待 ${INSTANCE_DISCOVERY_TIMEOUT_MS}ms 后仍未发现存活实例,跳过`);
|
|
107
114
|
return null;
|
|
@@ -181,10 +188,10 @@ export function startServiceProxy(controlChannel, providerAid, configuredService
|
|
|
181
188
|
let registered = 0;
|
|
182
189
|
for (const svc of services) {
|
|
183
190
|
if (stopped)
|
|
184
|
-
return;
|
|
191
|
+
return { registered: 0, gatewayRegistered: false };
|
|
185
192
|
const endpoint = await resolveEndpoint(svc);
|
|
186
193
|
if (stopped)
|
|
187
|
-
return;
|
|
194
|
+
return { registered: 0, gatewayRegistered: false };
|
|
188
195
|
if (!endpoint)
|
|
189
196
|
continue;
|
|
190
197
|
try {
|
|
@@ -202,10 +209,18 @@ export function startServiceProxy(controlChannel, providerAid, configuredService
|
|
|
202
209
|
}
|
|
203
210
|
if (registered === 0) {
|
|
204
211
|
logger.warn(`${LOG} 没有成功注册任何服务,不启动隧道`);
|
|
205
|
-
return;
|
|
212
|
+
return { registered: 0, gatewayRegistered: false };
|
|
206
213
|
}
|
|
207
214
|
if (stopped)
|
|
208
|
-
return;
|
|
215
|
+
return { registered: 0, gatewayRegistered: false };
|
|
216
|
+
let gatewayRegistered = false;
|
|
217
|
+
try {
|
|
218
|
+
await proxyClient.registerServicesWithGateway();
|
|
219
|
+
gatewayRegistered = true;
|
|
220
|
+
}
|
|
221
|
+
catch (e) {
|
|
222
|
+
logger.warn(`${LOG} Gateway 登记暂不可用,隧道后台继续重试: ${e?.message || e}`);
|
|
223
|
+
}
|
|
209
224
|
// 常驻持久隧道(内部自带指数退避重连 + client 缺失时自动等待)。
|
|
210
225
|
// 不 await:后台运行,不阻塞 daemon 启动。
|
|
211
226
|
proxyClient
|
|
@@ -217,13 +232,22 @@ export function startServiceProxy(controlChannel, providerAid, configuredService
|
|
|
217
232
|
logger.error(`${LOG} serveForever 异常退出: ${e?.message || e}`);
|
|
218
233
|
});
|
|
219
234
|
logger.info(`${LOG} ✓ 已启动,provider=${providerAid},注册 ${registered} 个服务`);
|
|
235
|
+
return { registered, gatewayRegistered };
|
|
220
236
|
}
|
|
221
237
|
catch (e) {
|
|
222
238
|
logger.warn(`${LOG} 启动失败(不影响 daemon 主流程): ${e?.message || e}`);
|
|
239
|
+
throw e;
|
|
223
240
|
}
|
|
224
241
|
};
|
|
225
|
-
|
|
242
|
+
const ready = run();
|
|
243
|
+
void ready.catch(() => { });
|
|
226
244
|
return {
|
|
245
|
+
ready,
|
|
246
|
+
unregister: async (serviceNames) => {
|
|
247
|
+
if (!proxyClient || serviceNames.length === 0)
|
|
248
|
+
return;
|
|
249
|
+
await proxyClient.unregisterServicesFromGateway(serviceNames);
|
|
250
|
+
},
|
|
227
251
|
stop: () => {
|
|
228
252
|
stopped = true;
|
|
229
253
|
try {
|