evolcore 0.0.48 → 0.0.50
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 +97 -0
- package/bin/ecmsg.js +9 -4
- package/dist/ability/caller/authorization.js +21 -0
- package/dist/ability/caller/command.js +164 -0
- package/dist/ability/caller/contract.js +102 -0
- package/dist/ability/caller/daemon.js +158 -0
- package/dist/ability/caller/service.js +380 -0
- package/dist/ability/command-contract.js +5 -0
- package/dist/ability/daemon.js +5 -1
- package/dist/ability/interop-v1.js +10 -3
- package/dist/ability/management.js +1 -0
- package/dist/agent-template/jobs.js +173 -1
- package/dist/agent-template/runtime.js +285 -8
- package/dist/agent-template/service.js +1159 -40
- package/dist/agent-template/types.js +2 -1
- package/dist/agents/baseagent-availability.js +27 -3
- package/dist/agents/baseagent-capability-adapter.js +102 -0
- package/dist/agents/baseagent-plugin-descriptor.js +274 -0
- package/dist/agents/baseagent-plugin-loader.js +145 -0
- package/dist/agents/baseagent.js +68 -2
- package/dist/agents/claude-gateway/agent-registration.js +389 -0
- package/dist/agents/claude-gateway/binding.js +96 -0
- package/dist/agents/claude-gateway/inbox.js +138 -0
- package/dist/agents/claude-gateway/index.js +125 -0
- package/dist/agents/claude-gateway/listing.js +330 -0
- package/dist/agents/claude-gateway/router.js +328 -0
- package/dist/agents/claude-gateway/sessions.js +128 -0
- package/dist/agents/claude-gateway/terminal.js +250 -0
- package/dist/agents/claude-gateway/transcript.js +272 -0
- package/dist/agents/claude-gateway/types.js +14 -0
- package/dist/agents/claude-runner.js +6 -10
- package/dist/agents/codex-runner.js +9 -2
- package/dist/agents/{gemini-runner.js → gemini/gemini-runner.js} +17 -17
- package/dist/{core/session/adapters → agents/gemini}/gemini-session-file-adapter.js +2 -2
- package/dist/agents/gemini/index.js +51 -0
- package/dist/aun/aid/control-aid.js +52 -32
- package/dist/aun/group/invite-service.js +6 -36
- package/dist/aun/group/operations.js +6 -0
- package/dist/aun/msg/mention-schema.js +1 -1
- package/dist/aun/msg/p2p.js +31 -2
- package/dist/aun/msg/upload.js +126 -3
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +1175 -457
- package/dist/cli/ability-command.js +42 -0
- package/dist/cli/agent-command.js +20 -1
- package/dist/cli/agent-create.js +78 -18
- package/dist/cli/agent-template.js +5 -3
- package/dist/cli/agent.js +91 -0
- package/dist/cli/aun-commands.js +92 -34
- package/dist/cli/bench.js +5 -2
- package/dist/cli/config.js +22 -6
- package/dist/cli/daemon-commands.js +245 -101
- package/dist/cli/directory.js +6 -1
- package/dist/cli/ecmsg-gateway.js +11 -9
- package/dist/cli/index.js +30 -5
- package/dist/cli/init.js +39 -63
- package/dist/cli/managed-command-guard.js +3 -0
- package/dist/cli/menu-client.js +32 -7
- package/dist/cli/model.js +20 -5
- package/dist/cli/pay-command.js +30 -0
- package/dist/cli/provider-command.js +6 -2
- package/dist/cli/quota.js +89 -0
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/role.js +1 -0
- package/dist/cli/services-command.js +12 -9
- package/dist/cli/team-workspace-command.js +56 -2
- package/dist/cli/thread-command.js +78 -12
- package/dist/config/access-policy.js +16 -3
- package/dist/config/config-field-policy.js +88 -9
- package/dist/config/config-manager.js +97 -47
- package/dist/config/config-operation-service.js +22 -1
- package/dist/config/gateway-config.js +9 -8
- package/dist/config/owner-config.js +0 -16
- package/dist/config/peer-role-resolver.js +1 -7
- package/dist/config/providers-config.js +107 -20
- package/dist/config/providers-management.js +45 -21
- package/dist/config/resolved-config-op.js +4 -44
- package/dist/config/schema-migration.js +78 -5
- package/dist/config/schema-registry.js +52 -7
- package/dist/config-store.js +1309 -17
- package/dist/core/agent-application-service.js +220 -1
- package/dist/core/agent-ipc-registration.js +19 -2
- package/dist/core/agent-reload-coordinator.js +5 -0
- package/dist/core/agent-runtime.js +198 -54
- package/dist/core/auth/agent-delegation.js +14 -0
- package/dist/core/auth/delegation-authorization.js +33 -26
- package/dist/core/auth/operation-authorizer.js +16 -1
- package/dist/core/auth/operation-catalog.js +59 -7
- package/dist/core/baseagent-loader.js +30 -3
- package/dist/core/capability/capability-manager.js +16 -7
- package/dist/core/channel-runtime.js +4 -2
- package/dist/core/command/agent-control.js +20 -2
- package/dist/core/command/agent-template-menu.js +4 -3
- package/dist/core/command/cli-intent-parser.js +28 -0
- package/dist/core/command/command-handler.js +45 -2
- package/dist/core/command/menu-catalog.js +20 -4
- package/dist/core/command/menu-file-path.js +70 -0
- package/dist/core/command/menu-handler.js +97 -73
- package/dist/core/command/menu-protocol.js +29 -0
- package/dist/core/command/menu-query-batch.js +2 -2
- package/dist/core/command/private-mention-menu.js +71 -0
- package/dist/core/command/remote-shell.js +565 -0
- package/dist/core/command/slash-handler.js +17 -26
- package/dist/core/command/team-workspace-bootstrap.js +2 -1
- package/dist/core/command/topic-slash.js +7 -1
- package/dist/core/daemon-bootstrap.js +0 -4
- package/dist/core/daemon-control.js +58 -1
- package/dist/core/daemon-lifecycle.js +29 -7
- package/dist/core/evolagent-registry.js +18 -9
- package/dist/core/handoff/runtime.js +1 -1
- package/dist/core/host-snapshot.js +8 -3
- package/dist/core/initialization/service.js +3 -0
- package/dist/core/interaction-router.js +130 -0
- package/dist/core/ipc-registration.js +5 -0
- package/dist/core/memory/consolidation-context.js +2 -1
- package/dist/core/memory/consolidation.js +35 -64
- package/dist/core/message/aun-ipc-sender.js +213 -74
- package/dist/core/message/aun-request-registry.js +31 -0
- package/dist/core/message/contact-admission.js +91 -6
- package/dist/core/message/contact-pending-inbound.js +113 -0
- package/dist/core/message/contact-thread-approval.js +212 -0
- package/dist/core/message/im-renderer.js +40 -1
- package/dist/core/message/message-admission.js +5 -39
- package/dist/core/message/message-bridge.js +197 -45
- package/dist/core/message/message-log.js +32 -0
- package/dist/core/message/message-queue.js +102 -18
- package/dist/core/message/peer-mode.js +15 -4
- package/dist/core/message/response-engine.js +174 -26
- package/dist/core/message/send-options.js +37 -3
- package/dist/core/message/send-routing.js +11 -7
- package/dist/core/model/config-scope.js +6 -14
- package/dist/core/model/model-catalog.js +5 -5
- package/dist/core/model/model-diagnostics.js +19 -0
- package/dist/core/model/model-fallback.js +13 -2
- package/dist/core/ownership/owner-resolver.js +12 -86
- package/dist/core/pack-auth.js +7 -0
- package/dist/core/pack-install.js +1 -1
- package/dist/core/permission/ec-command-parser.js +288 -77
- package/dist/core/permission/protected-paths.js +64 -9
- package/dist/core/permission/services-path-acl.js +458 -0
- package/dist/core/permission/tool-policy.js +26 -10
- package/dist/core/relation/peer-identity.js +13 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +6 -2
- package/dist/core/session/adapters/codex-session-file-adapter.js +4 -0
- package/dist/core/session/session-manager.js +47 -10
- package/dist/core/session/session-mapper.js +16 -0
- package/dist/core/skill/index-generator.js +2 -3
- package/dist/core/skill/switch-resolver.js +3 -0
- package/dist/core/task/task-recovery-service.js +1 -0
- package/dist/core/thread/command-parser.js +4 -1
- package/dist/core/thread/ipc-operation.js +4 -2
- package/dist/core/thread/thread-operation.js +25 -10
- package/dist/core/thread/thread-service.js +294 -55
- package/dist/core/thread/topic-id.js +67 -2
- package/dist/core/thread/types.js +15 -1
- package/dist/directory/owner-directory-admission.js +11 -8
- package/dist/directory/owner-directory-cache.js +19 -0
- package/dist/directory/owner-directory-markdown.js +1 -1
- package/dist/directory/owner-directory-policy.js +5 -30
- package/dist/directory/owner-directory-request-operation.js +5 -2
- package/dist/eck/kit-renderer.js +3 -2
- package/dist/eck/message-renderer.js +28 -5
- package/dist/ecweb/basic-settings-service.js +5 -9
- package/dist/ecweb/providers-service.js +4 -2
- package/dist/ecweb/runtime/supervisor.js +36 -8
- package/dist/event-center/center-config.js +9 -5
- package/dist/event-center/dispatcher.js +10 -1
- package/dist/event-center/ipc-operation.js +19 -0
- package/dist/event-center/registry.js +20 -5
- package/dist/event-center/runtime.js +10 -7
- package/dist/index.js +120 -41
- package/dist/ipc.js +83 -3
- package/dist/outputs/authorization.js +16 -0
- package/dist/outputs/cards.js +336 -0
- package/dist/outputs/events.js +3 -2
- package/dist/outputs/protocol.js +1 -0
- package/dist/outputs/service.js +2 -15
- package/dist/paths.js +48 -1
- package/dist/pay/command.js +38 -0
- package/dist/pay/protocol.js +136 -0
- package/dist/pay/runtime.js +188 -0
- package/dist/pay/service.js +384 -0
- package/dist/pay/store.js +81 -0
- package/dist/response-system/engines/v1/proactive-flow.js +29 -2
- package/dist/services/dispatcher.js +23 -5
- package/dist/services/host/main.js +388 -0
- package/dist/services/host/protocol.js +118 -0
- package/dist/services/host/resident.js +310 -0
- package/dist/services/host-client.js +386 -0
- package/dist/services/host-deploy.js +180 -0
- package/dist/services/host-launch.js +117 -0
- package/dist/services/host-recycle.js +203 -0
- package/dist/services/host-runtime.js +802 -0
- package/dist/services/idempotency.js +44 -86
- package/dist/services/index-generator.js +4 -3
- package/dist/services/index.js +204 -22
- package/dist/services/ipc-operation.js +288 -44
- package/dist/services/pack-manager.js +1 -0
- package/dist/services/script-runner.js +515 -83
- package/dist/services/service-payload.js +13 -7
- package/dist/services/validation.js +109 -4
- package/dist/stats/budget.js +1 -1
- package/dist/stats/model-resolver.js +2 -2
- package/dist/stats/quota-query.js +95 -0
- package/dist/trigger/application-service.js +6 -4
- package/dist/trigger/local-files.js +19 -9
- package/dist/trigger/scheduler.js +22 -12
- package/dist/trigger/script-sandbox.js +51 -8
- package/dist/utils/aid-bind.js +3 -0
- package/dist/utils/atomic-write.js +22 -8
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +173 -1
- package/dist/utils/logger.js +2 -2
- package/dist/utils/media-cache.js +190 -43
- package/dist/utils/npm-ops.js +43 -8
- package/dist/utils/restart-safety.js +14 -1
- package/dist/utils/system-memory.js +113 -25
- package/dist/utils/systemd-lifecycle.js +154 -0
- package/dist/utils/windows-shell-trust.js +7 -3
- package/dist/workbench/service.js +1 -1
- package/kits/docs/INDEX.md +3 -2
- package/kits/docs/aun/AUN/346/266/210/346/201/257/347/261/273/345/236/213/344/270/216/345/261/236/346/200/247.md +1 -0
- package/kits/docs/channels/aun.md +1 -1
- package/kits/docs/evolcore/INDEX.md +9 -6
- package/kits/docs/evolcore/agent.md +36 -1
- package/kits/docs/evolcore/aid.md +45 -3
- package/kits/docs/evolcore/config.md +5 -2
- package/kits/docs/evolcore/directory.md +8 -9
- package/kits/docs/evolcore/group.md +2 -1
- package/kits/docs/evolcore/memory-tags.md +2 -0
- package/kits/docs/evolcore/menu-client.md +3 -3
- package/kits/docs/evolcore/menu-protocol.md +7 -0
- package/kits/docs/evolcore/model.md +3 -0
- package/kits/docs/evolcore/msg.md +77 -10
- package/kits/docs/evolcore/pay.md +34 -0
- package/kits/docs/evolcore/provider.md +22 -1
- package/kits/docs/evolcore/quota.md +54 -0
- package/kits/docs/evolcore/role.md +3 -0
- package/kits/docs/evolcore/services.md +46 -18
- package/kits/docs/evolcore/stats.md +2 -0
- package/kits/docs/evolcore/thread-chain.md +2 -0
- package/kits/docs/evolcore/tool-authorization.md +10 -0
- package/kits/docs/evolcore/trigger.md +2 -0
- package/kits/rules/01-overview.md +11 -32
- package/kits/rules/02-navigation.md +7 -0
- package/kits/rules/06-channel.md +3 -3
- package/kits/schemas/_meta.json +38 -5
- package/kits/schemas/agent-config.schema.20.json +24 -0
- package/kits/schemas/agent-config.schema.21.json +974 -0
- package/kits/schemas/agent-config.schema.22.json +977 -0
- package/kits/schemas/agent-config.schema.23.json +958 -0
- package/kits/schemas/daemon.schema.10.json +373 -0
- package/kits/schemas/daemon.schema.9.json +12 -0
- package/kits/schemas/defaults.schema.7.json +472 -0
- package/kits/schemas/providers.schema.3.json +18 -2
- package/kits/schemas/relation-config.schema.13.json +289 -0
- package/kits/skills/.switches.json +17 -1
- package/kits/skills/ability/SKILL.md +229 -34
- package/kits/skills/ability/STRUCTURE.md +333 -0
- package/kits/skills/ability/references/cli.md +208 -0
- package/kits/skills/ability/references/development.md +107 -37
- package/kits/skills/ability/references/management.md +106 -46
- package/kits/skills/ability/references/runtime-protocol.md +65 -63
- package/kits/skills/agent-output-cards/SKILL.md +64 -0
- package/kits/skills/ec-group/SKILL.md +8 -6
- package/kits/skills/ec-group/TASK.md +186 -0
- package/kits/skills/ec-group/WORKLOG.md +180 -0
- package/kits/skills/ec-group-collaboration/SKILL.md +3 -3
- package/kits/skills/ec-pay/SKILL.md +101 -0
- package/kits/skills/ec-pay/references/pay-cli.md +110 -0
- package/kits/skills/ec-provider/SKILL.md +58 -9
- package/kits/skills/{ec-service-proxy → ec-proxy}/SKILL.md +8 -5
- package/kits/skills/ec-service-call/SKILL.md +135 -0
- package/kits/skills/ec-service-pack/SKILL.md +277 -0
- package/kits/skills/ec-trigger/SKILL.md +1 -1
- package/kits/templates/memory-consolidation/notes.md +2 -2
- package/kits/templates/memory-consolidation/workflow.md +46 -0
- package/kits/templates/roles/visitor.json +1 -0
- package/kits/templates/system-fragments/channel.md +13 -4
- package/kits/templates/system-fragments/commands.md +5 -3
- package/kits/templates/system-fragments/directory-contacts.md +3 -4
- package/kits/templates/system-fragments/reply.md +1 -0
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +27 -128
- package/kits/templates/system-fragments/venue.md +27 -0
- package/package.json +4 -5
- package/scripts/agent-template/inspect.mjs +79 -29
- package/scripts/agent-template/overlay.mjs +20 -2
- package/scripts/agent-template/shared/common.mjs +24 -6
- package/scripts/agent-template/shared/team-schema.json +23 -5
- package/scripts/agent-template/shared/template-contract.mjs +107 -17
- package/scripts/agent-template/shared/template-package.mjs +254 -29
- package/scripts/agent-template/shared/template-runtime.mjs +145 -2
- package/scripts/agent-template/shared/template.mjs +67 -9
- package/scripts/agent-template/team-pack.mjs +132 -41
- package/scripts/agent-template/team-preview.mjs +249 -5
- package/kits/docs/aun/ABILITY_CALLING.md +0 -280
- package/kits/docs/evolcore/ability.md +0 -185
- package/kits/skills/ability/references/calling.md +0 -56
- package/kits/skills/ability/references/contract-checklist.md +0 -37
- package/kits/skills/ability/references/recovery.md +0 -27
- /package/dist/{core/capability/providers → agents/gemini}/gemini-capability-provider.js +0 -0
|
@@ -0,0 +1,565 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
4
|
+
import { killProcessTree } from '../../utils/cross-platform.js';
|
|
5
|
+
import { logger } from '../../utils/logger.js';
|
|
6
|
+
import { auditCommandAuthorization, hashArgv } from '../auth/authorization-audit.js';
|
|
7
|
+
import { parseLiteralShellCommand } from '../permission/ec-command-parser.js';
|
|
8
|
+
import { checkBlacklist, checkDangerousCommand } from '../permission/tool-policy.js';
|
|
9
|
+
import { sanitizeMenuLogValue } from './menu-protocol.js';
|
|
10
|
+
export const REMOTE_SHELL_WINDOW_MS = 30 * 60_000;
|
|
11
|
+
export const REMOTE_SHELL_IDLE_MS = 6 * 60_000;
|
|
12
|
+
const OUTPUT_BUFFER_BYTES = 8 * 1024 * 1024;
|
|
13
|
+
const TEXT_CHUNK_BYTES = 16 * 1024 - 256; // Leave room for message and fragment headers.
|
|
14
|
+
/**
|
|
15
|
+
* argv execution only; spawn supports detached groups (execFile does not forward
|
|
16
|
+
* detached to spawn). Keep pipes attached so cancellation waits for descendants.
|
|
17
|
+
*/
|
|
18
|
+
export function executeRemoteShellCommand(argv, cwd, remainingMs) {
|
|
19
|
+
const child = spawn(argv[0], argv.slice(1), {
|
|
20
|
+
shell: false, cwd, env: process.env, windowsHide: true,
|
|
21
|
+
detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'],
|
|
22
|
+
});
|
|
23
|
+
let settled = false;
|
|
24
|
+
let termination;
|
|
25
|
+
let code;
|
|
26
|
+
const stdout = [];
|
|
27
|
+
const stderr = [];
|
|
28
|
+
const capture = (stream, output) => {
|
|
29
|
+
const decoder = new StringDecoder('utf8');
|
|
30
|
+
let bytes = 0;
|
|
31
|
+
stream.on('data', (buffer) => {
|
|
32
|
+
const available = Math.max(0, OUTPUT_BUFFER_BYTES - bytes);
|
|
33
|
+
output.push(decoder.write(buffer.subarray(0, available)));
|
|
34
|
+
bytes += buffer.length;
|
|
35
|
+
if (bytes > OUTPUT_BUFFER_BYTES && code !== 'OUTPUT_LIMIT') {
|
|
36
|
+
code = 'OUTPUT_LIMIT';
|
|
37
|
+
void terminate();
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
stream.on('end', () => {
|
|
41
|
+
// Discard an incomplete UTF-8 character at the truncation boundary.
|
|
42
|
+
if (bytes <= OUTPUT_BUFFER_BYTES)
|
|
43
|
+
output.push(decoder.end());
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
capture(child.stdout, stdout);
|
|
47
|
+
capture(child.stderr, stderr);
|
|
48
|
+
child.stdin.end();
|
|
49
|
+
const timer = setTimeout(() => { code = 'WINDOW_EXPIRED'; void terminate(); }, Math.max(1, remainingMs));
|
|
50
|
+
timer.unref();
|
|
51
|
+
const result = new Promise((resolve) => {
|
|
52
|
+
child.once('error', (error) => { code = error.code ?? 'SPAWN_FAILED'; });
|
|
53
|
+
child.once('close', (exitCode, signal) => {
|
|
54
|
+
settled = true;
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
resolve({
|
|
57
|
+
stdout: stdout.join(''), stderr: stderr.join(''), exitCode,
|
|
58
|
+
...(signal ? { signal } : {}), ...(code ? { code } : {}),
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
function terminate() {
|
|
63
|
+
if (termination)
|
|
64
|
+
return termination;
|
|
65
|
+
if (!child.pid || settled)
|
|
66
|
+
return result.then(() => undefined);
|
|
67
|
+
const targetPid = child.pid;
|
|
68
|
+
killProcessTree(targetPid);
|
|
69
|
+
termination = new Promise((resolve) => {
|
|
70
|
+
// Escalate the entire group even if the parent exits before its descendants.
|
|
71
|
+
setTimeout(() => { killProcessTree(targetPid, true); resolve(); }, 250);
|
|
72
|
+
}).then(() => result).then(() => undefined);
|
|
73
|
+
return termination;
|
|
74
|
+
}
|
|
75
|
+
return { result, terminate };
|
|
76
|
+
}
|
|
77
|
+
/** Owner-only text management, deliberately separate from delegated tool authorization. */
|
|
78
|
+
export class RemoteShellService {
|
|
79
|
+
deps;
|
|
80
|
+
leases = new Map();
|
|
81
|
+
requests = new Map();
|
|
82
|
+
now;
|
|
83
|
+
disposed = false;
|
|
84
|
+
order = 0;
|
|
85
|
+
transportEpoch = 0;
|
|
86
|
+
barriers = new Map();
|
|
87
|
+
constructor(deps) {
|
|
88
|
+
this.deps = deps;
|
|
89
|
+
this.now = deps.now ?? (() => performance.now());
|
|
90
|
+
}
|
|
91
|
+
handles(input) {
|
|
92
|
+
if (input.selfAID !== this.deps.controlAid || input.channelType !== 'aun'
|
|
93
|
+
|| input.chatType !== 'private' || input.payloadType !== 'text' || this.disposed)
|
|
94
|
+
return false;
|
|
95
|
+
return /^\/exec(?:[ \t]|$)/.test(input.content)
|
|
96
|
+
|| input.content.replace(/[ \t]+$/, '') === '/stop'
|
|
97
|
+
|| this.leases.get(this.key(input))?.entered === true;
|
|
98
|
+
}
|
|
99
|
+
key(input) {
|
|
100
|
+
return JSON.stringify([
|
|
101
|
+
input.peerId, input.peerDeviceId, input.peerSlotId ?? '', input.threadId ?? input.replyContext?.threadId ?? '',
|
|
102
|
+
]);
|
|
103
|
+
}
|
|
104
|
+
sameOwner(owner, expected) {
|
|
105
|
+
return owner?.aid === expected.aid && owner.relationVersion === expected.relationVersion;
|
|
106
|
+
}
|
|
107
|
+
valid(lease) {
|
|
108
|
+
return !this.disposed && !lease.closing && this.deps.connected()
|
|
109
|
+
&& this.sameOwner(this.deps.currentOwner(), lease.owner)
|
|
110
|
+
&& this.now() < lease.deadline && (!!lease.running || this.now() < lease.idleDeadline);
|
|
111
|
+
}
|
|
112
|
+
async handleText(input) {
|
|
113
|
+
if (!this.handles(input) || this.disposed)
|
|
114
|
+
return;
|
|
115
|
+
if (!input.encrypted) {
|
|
116
|
+
this.audit(input, 'reject', 'E2EE_REQUIRED');
|
|
117
|
+
let owner;
|
|
118
|
+
try {
|
|
119
|
+
owner = await this.deps.refreshOwner();
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
this.audit(input, 'reject', 'OWNER_UNAVAILABLE');
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
// Explain the rejection only to the verified Owner's authenticated device.
|
|
126
|
+
// The control sender forces E2EE even though the incoming request was plaintext.
|
|
127
|
+
if (owner?.aid === input.peerId && input.peerDeviceId && input.messageId) {
|
|
128
|
+
try {
|
|
129
|
+
await this.send(input, 'E2EE_REQUIRED: 请在与 daemon AID 的私聊中开启端到端加密后重发 /exec 指令。此次请求未执行。', owner);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
this.audit(input, 'delivery', 'DELIVERY_FAILED');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const key = this.key(input);
|
|
138
|
+
const transportEpoch = this.transportEpoch;
|
|
139
|
+
const order = ++this.order;
|
|
140
|
+
const receivedLease = this.leases.get(key);
|
|
141
|
+
const prefixed = /^\/exec(?:[ \t]|$)/.test(input.content);
|
|
142
|
+
const command = prefixed ? input.content.slice(5).replace(/^[ \t]+/, '') : input.content;
|
|
143
|
+
// Bare /exec queries status; raw on/off/status/stop remain executable names.
|
|
144
|
+
const control = prefixed ? command.replace(/[ \t]+$/, '')
|
|
145
|
+
: input.content.replace(/[ \t]+$/, '') === '/stop' ? 'stop' : undefined;
|
|
146
|
+
const query = prefixed && control === '';
|
|
147
|
+
const requestKey = JSON.stringify([key, input.messageId]);
|
|
148
|
+
const fingerprint = createHash('sha256').update(input.content).digest('hex');
|
|
149
|
+
const previous = this.requests.get(requestKey);
|
|
150
|
+
const record = { fingerprint, state: 'pending', replies: [], bytes: 0 };
|
|
151
|
+
if (!previous && input.messageId && input.peerDeviceId) {
|
|
152
|
+
this.requests.set(requestKey, record);
|
|
153
|
+
this.releaseResultCaches();
|
|
154
|
+
}
|
|
155
|
+
let knownOwner = false;
|
|
156
|
+
try {
|
|
157
|
+
const owner = await this.deps.refreshOwner();
|
|
158
|
+
if (!owner)
|
|
159
|
+
throw new Error('OWNER_UNAVAILABLE');
|
|
160
|
+
if (owner.aid !== input.peerId)
|
|
161
|
+
throw new Error('DAEMON_OWNER_REQUIRED');
|
|
162
|
+
knownOwner = true;
|
|
163
|
+
record.owner = owner;
|
|
164
|
+
if (!input.peerDeviceId)
|
|
165
|
+
throw new Error('DEVICE_ID_REQUIRED');
|
|
166
|
+
if (!input.messageId)
|
|
167
|
+
throw new Error('MESSAGE_ID_REQUIRED');
|
|
168
|
+
if (this.disposed || !this.deps.connected() || transportEpoch !== this.transportEpoch
|
|
169
|
+
|| !this.sameOwner(this.deps.currentOwner(), owner))
|
|
170
|
+
throw new Error('REMOTE_SHELL_CLOSED');
|
|
171
|
+
if (previous) {
|
|
172
|
+
if (previous.fingerprint !== fingerprint) {
|
|
173
|
+
await this.reply(input, record, 'CONFLICT: 消息 ID 对应不同内容。');
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
if (previous.owner && !this.sameOwner(owner, previous.owner))
|
|
177
|
+
throw new Error('REMOTE_SHELL_CLOSED');
|
|
178
|
+
const lease = this.leases.get(key);
|
|
179
|
+
const replies = query || control === 'on' || control === 'off' || control === 'stop'
|
|
180
|
+
? [this.status(lease)] : previous.state === 'pending' ? ['命令已接收,正在处理。']
|
|
181
|
+
: previous.replies.length ? previous.replies : ['命令已处理,结果缓存已释放,不会重复执行。'];
|
|
182
|
+
for (const text of replies)
|
|
183
|
+
await this.send(input, text, owner);
|
|
184
|
+
}
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
let lease = this.leases.get(key);
|
|
188
|
+
if (lease && !lease.closing && !this.valid(lease)) {
|
|
189
|
+
const reason = !this.sameOwner(this.deps.currentOwner(), lease.owner) ? 'owner-changed'
|
|
190
|
+
: this.now() >= lease.deadline ? 'expired' : 'idle';
|
|
191
|
+
await this.close(key, lease, reason);
|
|
192
|
+
lease = this.leases.get(key);
|
|
193
|
+
}
|
|
194
|
+
if (control === 'on') {
|
|
195
|
+
if ((this.barriers.get(key) ?? 0) > order)
|
|
196
|
+
throw new Error('CANCELLED');
|
|
197
|
+
if (!lease) {
|
|
198
|
+
// No await after the verified identity: on/off cannot interleave creation here.
|
|
199
|
+
if (!this.sameOwner(this.deps.currentOwner(), owner) || !this.deps.connected() || this.disposed
|
|
200
|
+
|| transportEpoch !== this.transportEpoch) {
|
|
201
|
+
throw new Error('OWNER_UNAVAILABLE');
|
|
202
|
+
}
|
|
203
|
+
lease = {
|
|
204
|
+
owner, input, openedOrder: order, cwd: this.deps.cwd ?? process.cwd(), queue: [],
|
|
205
|
+
deadline: this.now() + (this.deps.windowMs ?? REMOTE_SHELL_WINDOW_MS),
|
|
206
|
+
idleDeadline: this.now() + (this.deps.idleMs ?? REMOTE_SHELL_IDLE_MS),
|
|
207
|
+
};
|
|
208
|
+
this.leases.set(key, lease);
|
|
209
|
+
this.arm(key, lease);
|
|
210
|
+
this.audit(input, 'on');
|
|
211
|
+
const opened = lease;
|
|
212
|
+
opened.entry = this.notice(input, `已进入终端操作状态。\n${this.status(opened)}\n可直接发送单条命令;/stop 或 /exec stop 取消执行,/exec off 退出。`, 'remote-shell.entered', owner).then(delivered => {
|
|
213
|
+
opened.entered = delivered;
|
|
214
|
+
return delivered;
|
|
215
|
+
});
|
|
216
|
+
try {
|
|
217
|
+
const delivered = await opened.entry;
|
|
218
|
+
if (!delivered || this.leases.get(key) !== opened || !this.valid(opened)) {
|
|
219
|
+
throw new Error('REMOTE_SHELL_CLOSED');
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
await this.close(key, opened, 'entry-failed');
|
|
224
|
+
throw error;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
else {
|
|
228
|
+
if (lease.entry && !lease.closing)
|
|
229
|
+
await lease.entry;
|
|
230
|
+
await this.reply(input, record, this.status(lease));
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
else if (control === 'off' || control === 'stop') {
|
|
234
|
+
this.barriers.set(key, Math.max(this.barriers.get(key) ?? 0, order));
|
|
235
|
+
if (lease && lease.openedOrder <= order) {
|
|
236
|
+
if (control === 'off')
|
|
237
|
+
await this.close(key, lease, 'manual');
|
|
238
|
+
else
|
|
239
|
+
await this.cancel(key, lease);
|
|
240
|
+
}
|
|
241
|
+
this.audit(input, control);
|
|
242
|
+
if (control === 'stop' || !lease) {
|
|
243
|
+
await this.reply(input, record, control === 'stop' && lease && !lease.closing
|
|
244
|
+
? '当前执行已取消,仍处于终端操作状态。' : this.status(this.leases.get(key)));
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
else if (query) {
|
|
248
|
+
await this.reply(input, record, this.status(lease));
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
if (!command.trim())
|
|
252
|
+
throw new Error('INVALID_ARGUMENT');
|
|
253
|
+
if (!lease || lease !== receivedLease || !this.valid(lease) || lease.stopping
|
|
254
|
+
|| (this.barriers.get(key) ?? 0) > order)
|
|
255
|
+
throw new Error('REMOTE_SHELL_CLOSED');
|
|
256
|
+
// Keep the original text intact: structural newlines must reach the literal parser.
|
|
257
|
+
lease.queue.push({ input, record, command });
|
|
258
|
+
this.pump(key, lease);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
record.state = 'done';
|
|
262
|
+
}
|
|
263
|
+
catch (error) {
|
|
264
|
+
const message = error instanceof Error ? error.message : '';
|
|
265
|
+
const code = /^[A-Z][A-Z_]+$/.test(message) ? message : 'REMOTE_SHELL_FAILED';
|
|
266
|
+
record.state = 'done';
|
|
267
|
+
if (code === 'DELIVERY_FAILED') {
|
|
268
|
+
this.audit(input, 'delivery', code);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
this.audit(input, 'reject', code);
|
|
272
|
+
if (!knownOwner && this.requests.get(requestKey) === record)
|
|
273
|
+
this.requests.delete(requestKey);
|
|
274
|
+
if (knownOwner) {
|
|
275
|
+
try {
|
|
276
|
+
await this.reply(input, record, `${code}: 未执行。`);
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
this.audit(input, 'delivery', 'DELIVERY_FAILED');
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
status(lease) {
|
|
285
|
+
if (!lease || (!lease.closing && !this.valid(lease)))
|
|
286
|
+
return '已关闭。';
|
|
287
|
+
if (lease.closing)
|
|
288
|
+
return '正在关闭,等待所属进程退出。';
|
|
289
|
+
if (lease.entry && !lease.entered)
|
|
290
|
+
return '正在进入终端操作状态,等待提示投递。';
|
|
291
|
+
const remaining = Math.max(0, Math.ceil((lease.deadline - this.now()) / 1000));
|
|
292
|
+
const idle = Math.ceil((this.deps.idleMs ?? REMOTE_SHELL_IDLE_MS) / 60_000);
|
|
293
|
+
return `已开启,剩余 ${remaining} 秒,空闲 ${idle} 分钟后关闭。`
|
|
294
|
+
+ (lease.running ? `\n正在执行 message_id=${lease.running.task.input.messageId}` : '\n当前无命令运行。')
|
|
295
|
+
+ (lease.queue.length ? `\n排队 ${lease.queue.length} 条。` : '');
|
|
296
|
+
}
|
|
297
|
+
arm(key, lease) {
|
|
298
|
+
if (lease.timer)
|
|
299
|
+
clearTimeout(lease.timer);
|
|
300
|
+
if (lease.closing)
|
|
301
|
+
return;
|
|
302
|
+
const expiry = Math.min(lease.running ? lease.deadline : Math.min(lease.deadline, lease.idleDeadline), this.now() + (this.deps.currentOwner()?.validForMs ?? Infinity));
|
|
303
|
+
lease.timer = setTimeout(() => {
|
|
304
|
+
if (this.leases.get(key) !== lease)
|
|
305
|
+
return;
|
|
306
|
+
if (!this.sameOwner(this.deps.currentOwner(), lease.owner)) {
|
|
307
|
+
void this.close(key, lease, 'owner-unavailable');
|
|
308
|
+
}
|
|
309
|
+
else if (this.now() >= lease.deadline) {
|
|
310
|
+
void this.close(key, lease, 'expired');
|
|
311
|
+
}
|
|
312
|
+
else if (!lease.running && this.now() >= lease.idleDeadline) {
|
|
313
|
+
void this.close(key, lease, 'idle');
|
|
314
|
+
}
|
|
315
|
+
else
|
|
316
|
+
this.arm(key, lease); // Ownership evidence may have been refreshed.
|
|
317
|
+
}, Math.max(1, expiry - this.now()));
|
|
318
|
+
lease.timer.unref();
|
|
319
|
+
}
|
|
320
|
+
pump(key, lease) {
|
|
321
|
+
if (lease.running || lease.closing || lease.stopping)
|
|
322
|
+
return;
|
|
323
|
+
const task = lease.queue.shift();
|
|
324
|
+
if (!task) {
|
|
325
|
+
this.arm(key, lease);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
// Register running before awaiting ownership, so stop/off can cancel pre-start tasks.
|
|
329
|
+
const running = { task, done: Promise.resolve() };
|
|
330
|
+
lease.running = running;
|
|
331
|
+
this.arm(key, lease);
|
|
332
|
+
running.done = this.run(key, lease, running).catch(error => {
|
|
333
|
+
logger.warn(`[RemoteShell] command delivery failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
334
|
+
this.audit(task.input, 'delivery', 'DELIVERY_FAILED');
|
|
335
|
+
}).finally(() => {
|
|
336
|
+
task.record.state = 'done';
|
|
337
|
+
if (lease.running === running)
|
|
338
|
+
lease.running = undefined;
|
|
339
|
+
// Rejected input and status queries must not keep an unused window alive.
|
|
340
|
+
if (running.completedAt !== undefined) {
|
|
341
|
+
lease.idleDeadline = running.completedAt + (this.deps.idleMs ?? REMOTE_SHELL_IDLE_MS);
|
|
342
|
+
}
|
|
343
|
+
if (this.leases.get(key) === lease && !lease.closing && !lease.stopping)
|
|
344
|
+
this.pump(key, lease);
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
async run(key, lease, running) {
|
|
348
|
+
const { task } = running;
|
|
349
|
+
let owner;
|
|
350
|
+
try {
|
|
351
|
+
owner = await this.deps.refreshOwner();
|
|
352
|
+
}
|
|
353
|
+
catch { /* No valid evidence means no execution. */ }
|
|
354
|
+
if (this.leases.get(key) !== lease || !this.valid(lease) || task.cancelled
|
|
355
|
+
|| !this.sameOwner(owner, lease.owner)) {
|
|
356
|
+
this.audit(task.input, 'reject', task.cancelled ?? 'REMOTE_SHELL_CLOSED');
|
|
357
|
+
await this.reply(task.input, task.record, `${task.cancelled ?? 'REMOTE_SHELL_CLOSED'}: 未启动命令。`);
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
const parsed = parseLiteralShellCommand(task.command, { dialect: process.platform === 'win32' ? 'cmd' : 'posix' });
|
|
361
|
+
if (!parsed.ok) {
|
|
362
|
+
this.audit(task.input, 'reject', 'SHELL_COMPOSITION_NOT_ALLOWED');
|
|
363
|
+
await this.reply(task.input, task.record, `SHELL_COMPOSITION_NOT_ALLOWED: ${parsed.issue}`);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const blacklist = checkBlacklist('Bash', { command: task.command });
|
|
367
|
+
const danger = checkDangerousCommand('Bash', { command: task.command });
|
|
368
|
+
if (blacklist.behavior === 'deny' || danger.isDangerous) {
|
|
369
|
+
const kind = danger.isDangerous ? danger.kind : 'forbidden';
|
|
370
|
+
this.audit(task.input, 'reject', 'DANGEROUS_COMMAND_BLOCKED', parsed.argv, kind);
|
|
371
|
+
await this.reply(task.input, task.record, `DANGEROUS_COMMAND_BLOCKED: ${kind}`);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const started = this.now();
|
|
375
|
+
this.audit(task.input, 'start', undefined, parsed.argv, undefined, undefined, undefined, lease.cwd);
|
|
376
|
+
let result;
|
|
377
|
+
try {
|
|
378
|
+
running.execution = (this.deps.execute ?? executeRemoteShellCommand)(parsed.argv, lease.cwd, lease.deadline - this.now());
|
|
379
|
+
result = await running.execution.result;
|
|
380
|
+
if (result.code === 'OUTPUT_LIMIT' || result.code === 'WINDOW_EXPIRED')
|
|
381
|
+
await running.execution.terminate();
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
result = { stdout: '', stderr: '', exitCode: null, code: 'SPAWN_FAILED' };
|
|
385
|
+
}
|
|
386
|
+
running.completedAt = this.now();
|
|
387
|
+
const code = task.cancelled ?? result.code;
|
|
388
|
+
this.audit(task.input, 'finish', code, parsed.argv, undefined, result.exitCode, this.now() - started, lease.cwd, result.signal);
|
|
389
|
+
const heading = `执行结果 · message_id=${task.input.messageId}\nexitCode: ${result.exitCode ?? 'null'}`
|
|
390
|
+
+ (result.signal ? `\nsignal: ${result.signal}` : '') + (code ? `\ncode: ${code}` : '');
|
|
391
|
+
for (const [name, output] of [['stdout', result.stdout], ['stderr', result.stderr]]) {
|
|
392
|
+
if (!output)
|
|
393
|
+
continue;
|
|
394
|
+
const chunks = this.chunks(output);
|
|
395
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
396
|
+
await this.reply(task.input, task.record, `message_id=${task.input.messageId} ${name} ${i + 1}/${chunks.length}\n${chunks[i]}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
await this.reply(task.input, task.record, heading);
|
|
400
|
+
}
|
|
401
|
+
chunks(text) {
|
|
402
|
+
const chunks = [];
|
|
403
|
+
let chunk = '';
|
|
404
|
+
let bytes = 0;
|
|
405
|
+
for (const character of text) {
|
|
406
|
+
const size = Buffer.byteLength(character);
|
|
407
|
+
if (bytes + size > TEXT_CHUNK_BYTES) {
|
|
408
|
+
chunks.push(chunk);
|
|
409
|
+
chunk = '';
|
|
410
|
+
bytes = 0;
|
|
411
|
+
}
|
|
412
|
+
chunk += character;
|
|
413
|
+
bytes += size;
|
|
414
|
+
}
|
|
415
|
+
if (chunk)
|
|
416
|
+
chunks.push(chunk);
|
|
417
|
+
return chunks;
|
|
418
|
+
}
|
|
419
|
+
canSend(input, expectedOwner) {
|
|
420
|
+
const owner = this.deps.currentOwner();
|
|
421
|
+
return this.deps.connected() && owner?.aid === input.peerId && !this.disposed
|
|
422
|
+
&& (!expectedOwner || this.sameOwner(owner, expectedOwner));
|
|
423
|
+
}
|
|
424
|
+
async send(input, text, expectedOwner) {
|
|
425
|
+
if (!this.canSend(input, expectedOwner))
|
|
426
|
+
return;
|
|
427
|
+
try {
|
|
428
|
+
await this.deps.send(input, text);
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
throw new Error('DELIVERY_FAILED');
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
async notice(input, text, subtype, owner) {
|
|
435
|
+
if (!this.canSend(input, owner))
|
|
436
|
+
return false;
|
|
437
|
+
try {
|
|
438
|
+
await this.deps.notice(input, text, subtype);
|
|
439
|
+
}
|
|
440
|
+
catch {
|
|
441
|
+
throw new Error('DELIVERY_FAILED');
|
|
442
|
+
}
|
|
443
|
+
return true;
|
|
444
|
+
}
|
|
445
|
+
async reply(input, record, text) {
|
|
446
|
+
// Keep bounded replay text; the request fingerprint remains even when output is released.
|
|
447
|
+
if (record.bytes + Buffer.byteLength(text) <= 128 * 1024) {
|
|
448
|
+
record.replies.push(text);
|
|
449
|
+
record.bytes += Buffer.byteLength(text);
|
|
450
|
+
}
|
|
451
|
+
else {
|
|
452
|
+
record.replies = [];
|
|
453
|
+
record.bytes = 128 * 1024 + 1;
|
|
454
|
+
}
|
|
455
|
+
await this.send(input, text, record.owner);
|
|
456
|
+
}
|
|
457
|
+
releaseResultCaches() {
|
|
458
|
+
// Retain fingerprints across off/on; release old text without ever rerunning a request.
|
|
459
|
+
if (this.requests.size <= 100)
|
|
460
|
+
return;
|
|
461
|
+
const old = [...this.requests.values()].slice(0, -100);
|
|
462
|
+
for (const record of old) {
|
|
463
|
+
record.replies = [];
|
|
464
|
+
record.bytes = 128 * 1024 + 1;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
cancel(key, lease) {
|
|
468
|
+
if (lease.cancellation)
|
|
469
|
+
return lease.cancellation;
|
|
470
|
+
lease.stopping = true;
|
|
471
|
+
const queued = lease.queue.splice(0);
|
|
472
|
+
for (const task of queued) {
|
|
473
|
+
task.cancelled = 'CANCELLED';
|
|
474
|
+
task.record.state = 'done';
|
|
475
|
+
this.audit(task.input, 'reject', 'CANCELLED');
|
|
476
|
+
}
|
|
477
|
+
const running = lease.running;
|
|
478
|
+
if (running)
|
|
479
|
+
running.task.cancelled = lease.closing === 'expired' ? 'WINDOW_EXPIRED' : 'CANCELLED';
|
|
480
|
+
lease.cancellation = (async () => {
|
|
481
|
+
// Delivery errors must never prevent process termination or queue cleanup.
|
|
482
|
+
if (running) {
|
|
483
|
+
await running.execution?.terminate();
|
|
484
|
+
await running.done;
|
|
485
|
+
}
|
|
486
|
+
for (const task of queued) {
|
|
487
|
+
try {
|
|
488
|
+
await this.reply(task.input, task.record, `CANCELLED: message_id=${task.input.messageId} 未启动。`);
|
|
489
|
+
}
|
|
490
|
+
catch {
|
|
491
|
+
this.audit(task.input, 'delivery', 'DELIVERY_FAILED');
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
lease.stopping = false;
|
|
495
|
+
if (!lease.closing && this.leases.get(key) === lease)
|
|
496
|
+
this.arm(key, lease);
|
|
497
|
+
})().finally(() => { lease.cancellation = undefined; });
|
|
498
|
+
return lease.cancellation;
|
|
499
|
+
}
|
|
500
|
+
close(key, lease, reason) {
|
|
501
|
+
if (lease.closure)
|
|
502
|
+
return lease.closure;
|
|
503
|
+
if (this.leases.get(key) !== lease)
|
|
504
|
+
return Promise.resolve();
|
|
505
|
+
lease.closing = reason;
|
|
506
|
+
if (lease.timer)
|
|
507
|
+
clearTimeout(lease.timer);
|
|
508
|
+
this.audit(lease.input, 'close', undefined, undefined, reason);
|
|
509
|
+
lease.closure = this.cancel(key, lease).then(async () => {
|
|
510
|
+
// An off racing the entry notice must send its exit notice after entry delivery.
|
|
511
|
+
await lease.entry?.catch(() => false);
|
|
512
|
+
if (lease.entered) {
|
|
513
|
+
const text = reason === 'idle' ? '空闲超时,已退出终端操作状态。'
|
|
514
|
+
: reason === 'expired' ? '终端窗口已到期,已退出终端操作状态。' : '已退出终端操作状态。';
|
|
515
|
+
try {
|
|
516
|
+
await this.notice(lease.input, text, 'remote-shell.exited', lease.owner);
|
|
517
|
+
}
|
|
518
|
+
catch {
|
|
519
|
+
this.audit(lease.input, 'delivery', 'DELIVERY_FAILED');
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
if (this.leases.get(key) === lease)
|
|
523
|
+
this.leases.delete(key);
|
|
524
|
+
});
|
|
525
|
+
return lease.closure;
|
|
526
|
+
}
|
|
527
|
+
async closeAll(reason) {
|
|
528
|
+
// Also invalidate on requests still awaiting authentication during a disconnect.
|
|
529
|
+
this.transportEpoch++;
|
|
530
|
+
await Promise.all([...this.leases].map(([key, lease]) => this.close(key, lease, reason)));
|
|
531
|
+
}
|
|
532
|
+
/** Called on Ownership updates, including validity expiry without an Owner change. */
|
|
533
|
+
revalidateOwner() {
|
|
534
|
+
for (const [key, lease] of this.leases) {
|
|
535
|
+
if (!this.sameOwner(this.deps.currentOwner(), lease.owner)) {
|
|
536
|
+
void this.close(key, lease, 'owner-changed');
|
|
537
|
+
}
|
|
538
|
+
else
|
|
539
|
+
this.arm(key, lease);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
async dispose() {
|
|
543
|
+
this.disposed = true;
|
|
544
|
+
await this.closeAll('shutdown');
|
|
545
|
+
this.requests.clear();
|
|
546
|
+
}
|
|
547
|
+
audit(input, action, code, argv, rule, exitCode, durationMs, cwd, signal) {
|
|
548
|
+
const failed = !!code || !!signal || (exitCode !== undefined && exitCode !== 0);
|
|
549
|
+
(this.deps.audit ?? auditCommandAuthorization)({
|
|
550
|
+
ts: Date.now(), source: 'control', operation: 'remote-shell.exec', scope: 'process', dangerous: true,
|
|
551
|
+
actorId: input.peerId, selfAid: this.deps.controlAid, channel: 'control', channelId: input.peerId,
|
|
552
|
+
role: 'none', processRole: this.deps.currentOwner()?.aid === input.peerId ? 'daemon-owner' : 'none',
|
|
553
|
+
isDaemonOwner: this.deps.currentOwner()?.aid === input.peerId, fromControlChannel: true,
|
|
554
|
+
requestId: input.messageId, messageId: input.messageId, action, name: 'remote-shell',
|
|
555
|
+
eventPhase: action, decisionSource: 'command', decision: code && action === 'reject' ? 'deny' : 'allow',
|
|
556
|
+
executed: action === 'start' || action === 'finish',
|
|
557
|
+
executionState: action === 'reject' ? 'blocked' : action === 'delivery' ? 'failed'
|
|
558
|
+
: action === 'finish' ? failed ? 'failed' : 'completed' : 'authorized',
|
|
559
|
+
...(argv ? { args: sanitizeMenuLogValue({ argv }), argvHash: hashArgv(argv) } : {}),
|
|
560
|
+
argsSummary: { deviceId: input.peerDeviceId, slotId: input.peerSlotId, cwd, signal,
|
|
561
|
+
...(action === 'close' ? { closeReason: rule } : {}) },
|
|
562
|
+
matchedRule: rule, code, ...(exitCode != null ? { exitCode } : {}), durationMs,
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
}
|
|
@@ -4,12 +4,12 @@ import { normalizeBaseagent, resolveBaseagentModelSelection } from '../../agents
|
|
|
4
4
|
import { buildEnvelope, isDeliveryTargetForChannel } from '../message/message-utils.js';
|
|
5
5
|
import { resolvePaths, getPackageRoot, daemonControlDir } from '../../paths.js';
|
|
6
6
|
import { logger } from '../../utils/logger.js';
|
|
7
|
-
import { shouldSuppressRealRestart, createRestartRequest, updateRestartRequest, removeRestartRequest } from '../../utils/restart-safety.js';
|
|
8
|
-
import { RESTART_REQUEST_ID_ENV } from '../../product.js';
|
|
7
|
+
import { shouldSuppressRealRestart, createRestartRequest, readRestartRequest, updateRestartRequest, removeRestartRequest } from '../../utils/restart-safety.js';
|
|
8
|
+
import { RESTART_REQUEST_ID_ENV, RUNTIME_HOME_ENV, SESSION_ID_ENV } from '../../product.js';
|
|
9
|
+
import { AGENT_DELEGATION_TOKEN_ENV } from '../auth/agent-delegation.js';
|
|
9
10
|
import crypto from 'crypto';
|
|
10
11
|
import path from 'path';
|
|
11
12
|
import fs from 'fs';
|
|
12
|
-
import { ensureFreshPackageVersionInfo } from '../../utils/package-version-info.js';
|
|
13
13
|
import { executeUpgradeAction, formatUpgradeResult, subscribeUpgradeJob } from '../../utils/upgrade-jobs.js';
|
|
14
14
|
import { loadDaemonConfig } from '../../config-store.js';
|
|
15
15
|
import { formatPairingCodeMessage } from '../../ecweb/pairing.js';
|
|
@@ -37,7 +37,7 @@ import { chatmodeFieldForPeer, isChatMode, isPrivateChatmodeRoleLocked, resolveC
|
|
|
37
37
|
import { normalizePermissionMode as normalizePermissionModeContract, PUBLIC_PERMISSION_MODES } from '../permission/mode.js';
|
|
38
38
|
import { isManagementRole } from '../../config/builtin-roles.js';
|
|
39
39
|
import { isSystemControlChannel } from '../system-channels.js';
|
|
40
|
-
import {
|
|
40
|
+
import { resolveCliEntry, launchMonitorAndConfirm, isProcessRunning } from '../../utils/cross-platform.js';
|
|
41
41
|
import { hasLiveRestartMonitor } from '../../utils/instance-registry.js';
|
|
42
42
|
import { guardIdleCommand, guardGroupSlashCommand, guardKnownCommand, guardRoleCommand, guardThreadCommand, isRecognizedSlashCommand, normalizeSlashContent, parseFullAccessCommand, probeSessionActivity, } from './slash-gate.js';
|
|
43
43
|
import { MAX_AUN_ATTACHMENT_SIZE } from '../../aun/msg/upload.js';
|
|
@@ -3202,12 +3202,6 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
|
|
|
3202
3202
|
autoUpgrade = false;
|
|
3203
3203
|
}
|
|
3204
3204
|
}
|
|
3205
|
-
if (!suppressRealRestart && autoUpgrade) {
|
|
3206
|
-
await ensureFreshPackageVersionInfo(undefined, {
|
|
3207
|
-
source: 'slash-restart',
|
|
3208
|
-
log: message => logger.info(`[System] ${message}`),
|
|
3209
|
-
});
|
|
3210
|
-
}
|
|
3211
3205
|
const restartInfo = {
|
|
3212
3206
|
channel,
|
|
3213
3207
|
channelId,
|
|
@@ -3220,12 +3214,9 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
|
|
|
3220
3214
|
...(restartReplyContext?.replyToMessageId ? { rootId: restartReplyContext.replyToMessageId } : {}),
|
|
3221
3215
|
};
|
|
3222
3216
|
if (!suppressRealRestart) {
|
|
3223
|
-
//
|
|
3224
|
-
//
|
|
3225
|
-
|
|
3226
|
-
const monitorEntry = resolveMonitorLaunch(getPackageRoot(), path.join(resolvePaths().root, 'data', 'monitor-stage'));
|
|
3227
|
-
if (monitorEntry.note)
|
|
3228
|
-
logger.info(`[System] ${monitorEntry.note}`);
|
|
3217
|
+
// CLI owns backend selection for Menu and slash alike. In particular,
|
|
3218
|
+
// a detached monitor cannot survive shutdown of its owning systemd unit.
|
|
3219
|
+
const monitorEntry = resolveCliEntry(getPackageRoot());
|
|
3229
3220
|
if (!fs.existsSync(monitorEntry.entry)) {
|
|
3230
3221
|
logger.error(`[System] Refusing restart: restart-monitor entry not found: ${monitorEntry.entry}`);
|
|
3231
3222
|
return { code: 'RESTART_ENTRY_MISSING', entry: monitorEntry.entry };
|
|
@@ -3235,18 +3226,20 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
|
|
|
3235
3226
|
const pendingFile = path.join(controlDir, 'restart-pending.json');
|
|
3236
3227
|
if (await hasLiveRestartMonitor()
|
|
3237
3228
|
|| !createRestartRequest(pendingFile, restartInfo, isProcessRunning)) {
|
|
3238
|
-
if (monitorEntry.stageDir)
|
|
3239
|
-
cleanupMonitorStage(monitorEntry.stageDir);
|
|
3240
3229
|
return { code: 'RESTART_PENDING_CONFIRMATION', reason: '已有重启请求正在处理', requestId: restartInfo.requestId };
|
|
3241
3230
|
}
|
|
3242
|
-
const confirmation = await launchMonitorAndConfirm([...monitorEntry.args, 'restart
|
|
3231
|
+
const confirmation = await launchMonitorAndConfirm([...monitorEntry.args, 'restart', autoUpgrade ? '--apply-package-upgrades' : '--skip-package-upgrades'], {
|
|
3232
|
+
[RUNTIME_HOME_ENV]: resolvePaths().root, [RESTART_REQUEST_ID_ENV]: restartInfo.requestId,
|
|
3233
|
+
[SESSION_ID_ENV]: '', [AGENT_DELEGATION_TOKEN_ENV]: '',
|
|
3234
|
+
}, () => ['accepted', 'ready'].includes(readRestartRequest(pendingFile, restartInfo.requestId)?.status ?? ''), pid => hasLiveRestartMonitor({ excludePid: pid, requestId: restartInfo.requestId, phase: 'accepted' }), {
|
|
3243
3235
|
requestId: restartInfo.requestId,
|
|
3244
3236
|
logFilePath: path.join(resolvePaths().logs, `restart-launch-${restartInfo.requestId}.log`),
|
|
3245
3237
|
onSpawn: pid => { updateRestartRequest(pendingFile, restartInfo.requestId, { launcherPid: pid }); },
|
|
3246
3238
|
isPendingInRegistry: () => hasLiveRestartMonitor({ requestId: restartInfo.requestId }),
|
|
3247
3239
|
});
|
|
3248
3240
|
if (!confirmation.ok) {
|
|
3249
|
-
|
|
3241
|
+
const pending = readRestartRequest(pendingFile, restartInfo.requestId);
|
|
3242
|
+
if (confirmation.pending || (pending?.backend === 'systemd' && ['requested', 'accepted'].includes(pending.status))) {
|
|
3250
3243
|
logger.warn(`[System] Restart ownership remains unconfirmed (requestId=${restartInfo.requestId}, PID=${confirmation.pid ?? 'unknown'})`);
|
|
3251
3244
|
return {
|
|
3252
3245
|
code: 'RESTART_PENDING_CONFIRMATION',
|
|
@@ -3255,15 +3248,13 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
|
|
|
3255
3248
|
...(confirmation.pid ? { pid: confirmation.pid } : {}),
|
|
3256
3249
|
};
|
|
3257
3250
|
}
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
cleanupMonitorStage(monitorEntry.stageDir);
|
|
3261
|
-
removeRestartRequest(pendingFile, restartInfo.requestId);
|
|
3251
|
+
if (pending?.backend !== 'systemd')
|
|
3252
|
+
removeRestartRequest(pendingFile, restartInfo.requestId);
|
|
3262
3253
|
logger.error(`[System] Refusing restart: restart-monitor did not come up (${confirmation.reason})`);
|
|
3263
3254
|
for (const line of (confirmation.stderrTail ?? '').split(/\r?\n/).filter(Boolean).slice(-8)) {
|
|
3264
3255
|
logger.error(`[System] | ${line}`);
|
|
3265
3256
|
}
|
|
3266
|
-
return { code: 'RESTART_MONITOR_DEAD', reason: confirmation.reason ?? 'unknown' };
|
|
3257
|
+
return { code: 'RESTART_MONITOR_DEAD', reason: pending?.reason ?? confirmation.reason ?? 'unknown' };
|
|
3267
3258
|
}
|
|
3268
3259
|
}
|
|
3269
3260
|
else {
|
|
@@ -3301,7 +3292,7 @@ export async function handleSlashCommand(content, channel, channelId, sendMessag
|
|
|
3301
3292
|
});
|
|
3302
3293
|
await adapter.send(envelope, {
|
|
3303
3294
|
kind: 'system.notice',
|
|
3304
|
-
text: '🔄
|
|
3295
|
+
text: '🔄 重启请求已接管,服务正在重启;完成后会另行通知。',
|
|
3305
3296
|
subtype: 'system.restart.pending',
|
|
3306
3297
|
});
|
|
3307
3298
|
// 等待消息发送完成后再延迟 kill
|