agentxgo 0.1.2-rc.1 → 0.1.2-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -59,8 +59,8 @@ export class HttpBotRuntimeClient {
59
59
  reconcile(request) {
60
60
  return this.http.post('/bot-runtime/v1/reconcile', request);
61
61
  }
62
- async inspectNativeRecovery(context) {
63
- return botNativeRecoveryInspection(await this.http.post('/bot-runtime/v1/recovery/inspect', { context }), { provider: this.provider, executionId: context.executionId });
62
+ async inspectNativeRecovery(context, signal) {
63
+ return botNativeRecoveryInspection(await this.http.post('/bot-runtime/v1/recovery/inspect', { context }, undefined, undefined, signal), { provider: this.provider, executionId: context.executionId });
64
64
  }
65
65
  reports(context, after) {
66
66
  return this.http.post('/bot-runtime/v1/reports/poll', { context, after });
@@ -67,19 +67,23 @@ export class HostAgentIMAssembly {
67
67
  await this.disconnect();
68
68
  return;
69
69
  }
70
- const binding = {
70
+ const granted = {
71
71
  bindingId: grant.bindingId,
72
- revision: old?.binding.revision ?? 1,
72
+ revision: 1,
73
73
  identity: { homeserver: grant.homeserver, user_id: grant.userId, device_id: grant.deviceId },
74
74
  rooms: grant.roomIds,
75
75
  };
76
76
  if (old &&
77
- canonicalBotJson({ ...old.binding, rooms: [...old.binding.rooms].sort() }) !==
78
- canonicalBotJson(binding)) {
77
+ (canonicalBotJson(old.binding.identity) !== canonicalBotJson(granted.identity) ||
78
+ canonicalBotJson([...old.binding.rooms].sort()) !==
79
+ canonicalBotJson([...granted.rooms].sort()))) {
79
80
  this.reason = 'AGENTIM_EXISTING_BINDING_MISMATCH';
80
81
  await this.disconnect();
81
82
  return;
82
83
  }
84
+ // A new grant may authorize the same device and rooms under a new Bridge ID.
85
+ // The local binding still identifies the original checkpoint and idempotency records.
86
+ const binding = old?.binding ?? granted;
83
87
  const active = this.channel;
84
88
  if (active?.executionId === executionId && sameBinding(active.grant, grant)) {
85
89
  active.grant = grant;
@@ -166,7 +170,5 @@ export class HostAgentIMAssembly {
166
170
  }
167
171
  /** 续期更新原租约,不重置设备、房间或已知输入。 */
168
172
  function sameBinding(a, b) {
169
- const { expiresAtMs: _untilA, ...identityA } = a;
170
- const { expiresAtMs: _untilB, ...identityB } = b;
171
- return canonicalBotJson(identityA) === canonicalBotJson(identityB);
173
+ return canonicalBotJson({ ...a, expiresAtMs: b.expiresAtMs }) === canonicalBotJson(b);
172
174
  }
@@ -1,5 +1,5 @@
1
1
  import { callDirectAgentIM, directAgentIMFailure, directAgentIMDigest, directAgentIMCatalogue, directAgentIMOperation, directAgentIMSchema, directAgentIMInput, communicationReplyReceipt, } from "../vendor/@agent-stack/adapter-agentim/dist/local.js";
2
- import { botObject, botId, botInteger } from "../vendor/@agent-stack/contracts/dist/index.js";
2
+ import { BotContractError, botObject, botId, botInteger } from "../vendor/@agent-stack/contracts/dist/index.js";
3
3
  /** SDK 拥有业务权限和效果;Host 仅持原写调用摘要/结果,未知写绝不换身份重发。 */
4
4
  export class AgentIMCalls {
5
5
  config;
@@ -38,11 +38,25 @@ export class AgentIMCalls {
38
38
  return Promise.resolve({ input: original });
39
39
  return communicationReplyReceipt(this.config, original, request.sdkRequestId, signal ? { signal } : {}).then((reply) => ({ input: original, reply }));
40
40
  }
41
- const operationId = botId(request.operationId);
41
+ if (request.operation !== 'schema' && request.operation !== 'call')
42
+ return Promise.reject(new Error('AGENTIM_OPERATION_INVALID'));
43
+ let operationId;
44
+ try {
45
+ operationId = botId(request.operationId);
46
+ }
47
+ catch (error) {
48
+ if (!(error instanceof BotContractError))
49
+ throw error;
50
+ return Promise.resolve({
51
+ state: 'REJECTED',
52
+ disposition: 'NOT_SENT',
53
+ code: 'AGENTIM_OPERATION_ID_REQUIRED',
54
+ field: 'operationId',
55
+ hint: 'Pass the SDK operationId at the top level. The SDK schema describes only input.',
56
+ });
57
+ }
42
58
  if (request.operation === 'schema')
43
59
  return Promise.resolve(directAgentIMSchema(operationId));
44
- if (request.operation !== 'call')
45
- return Promise.reject(new Error('AGENTIM_OPERATION_INVALID'));
46
60
  const operation = directAgentIMOperation(operationId), id = botId(request.requestId);
47
61
  const input = directAgentIMInput(operationId, request.input, id);
48
62
  const digest = directAgentIMDigest(operationId, input);
@@ -106,7 +106,7 @@ export class BotHostCoordinator {
106
106
  records: this.records.inspect(),
107
107
  };
108
108
  }
109
- inspectNativeRecovery = () => this.recovery.inspectNative();
109
+ inspectNativeRecovery = (signal) => this.recovery.inspectNative(signal);
110
110
  inspectActivation(requestId, sourceId) {
111
111
  return this.activation.inspect(requestId, sourceId);
112
112
  }
@@ -52,6 +52,7 @@ function guidance(code) {
52
52
  return { nextStep: { program: 'agentxgo-bot-host', args: ['help', 'component', '--json'] } };
53
53
  return code &&
54
54
  [
55
+ 'BOT_COMPONENT_DEVICE_REQUIRED',
55
56
  'BOT_COMPONENT_MACOS_GUARD_REQUIRED',
56
57
  'BOT_COMPONENT_USER_SUPERVISOR_UNAVAILABLE',
57
58
  'BOT_COMPONENT_SUPERVISOR_UNAVAILABLE',
@@ -12,6 +12,8 @@ const startupCodes = new Set([
12
12
  'BOT_DEPLOYMENT_RUNTIME_PROCESS_CHANGED',
13
13
  'BOT_DEPLOYMENT_RUNTIME_RESPONSE_LIMIT',
14
14
  'BOT_DEPLOYMENT_RUNTIME_RESPONSE_INVALID',
15
+ 'BOT_DEPLOYMENT_ACCOUNT_SHARED_WITH_OTHER_PROCESS',
16
+ 'BOT_DEPLOYMENT_FINITE_LIMIT_REQUIRED',
15
17
  'BOT_DEPLOYMENT_PRIVATE_MANIFEST_REQUIRED',
16
18
  'BOT_DEPLOYMENT_ABSOLUTE_MANIFEST_REQUIRED',
17
19
  'BOT_PROJECT_ROOT_PRIVATE_REQUIRED',
@@ -26,6 +26,37 @@ function immutableLimit(path, system) {
26
26
  if (meta.uid !== 0 || (meta.mode & 0o022) !== 0 || meta.symlink || !meta.file)
27
27
  return denied('IMMUTABLE_KERNEL_LIMITS_REQUIRED');
28
28
  }
29
+ function boundedGroup(profile, cgroup, system) {
30
+ const companion = cgroup !== profile.cgroup;
31
+ const path = '/sys/fs/cgroup' + cgroup;
32
+ if (system.realpath(path) !== path || !system.metadata(path).directory)
33
+ return denied('CGROUP_PATH_INVALID');
34
+ for (const file of ['memory.max', 'memory.swap.max', 'pids.max', 'cpu.max'])
35
+ immutableLimit(path + '/' + file, system);
36
+ // A user manager can delegate within its own cgroup. Its parent must remain
37
+ // root-controlled so its processes cannot leave the approved envelope.
38
+ for (let ancestor = companion ? dirname(path) : path; beneath('/sys/fs/cgroup', ancestor); ancestor = dirname(ancestor))
39
+ immutableLimit(ancestor + '/cgroup.procs', system);
40
+ const swap = system.read(path + '/memory.swap.max').trim();
41
+ if (swap !== '0' && (!companion || number(swap) > 256 * 1024 * 1024))
42
+ return denied('SWAP_LIMIT_REQUIRED');
43
+ const memoryBytes = number(system.read(path + '/memory.max'));
44
+ const pids = number(system.read(path + '/pids.max'));
45
+ const cpu = system
46
+ .read(path + '/cpu.max')
47
+ .trim()
48
+ .split(/\s+/);
49
+ if (cpu.length !== 2)
50
+ return denied('CPU_LIMIT_INVALID');
51
+ const cpuCores = number(cpu[0]) / number(cpu[1]);
52
+ const maxMemoryMiB = companion ? 4096 : profile.role === 'host' ? 512 : 2048;
53
+ if (memoryBytes < 64 * 1024 * 1024 ||
54
+ memoryBytes > maxMemoryMiB * 1024 * 1024 ||
55
+ pids > (companion ? 256 : 128) ||
56
+ cpuCores > 2)
57
+ return denied('RESOURCE_ENVELOPE_EXCEEDED');
58
+ return { role: profile.role, memoryBytes, pids, cpuCores };
59
+ }
29
60
  export function kernelProfiles(profiles, system) {
30
61
  if (system.platform !== 'linux' || system.uid <= 0 || !system.cgroupV2())
31
62
  return denied('DEDICATED_LINUX_ACCOUNT_REQUIRED');
@@ -33,34 +64,13 @@ export function kernelProfiles(profiles, system) {
33
64
  if (self !== host.cgroup || host.uid !== system.uid)
34
65
  return denied('HOST_CGROUP_MISMATCH');
35
66
  const limits = profiles.map((p) => {
36
- const path = '/sys/fs/cgroup' + p.cgroup;
37
- if (system.realpath(path) !== path || !system.metadata(path).directory)
38
- return denied('CGROUP_PATH_INVALID');
39
- for (const file of ['memory.max', 'memory.swap.max', 'pids.max', 'cpu.max']) {
40
- immutableLimit(path + '/' + file, system);
41
- }
42
- // Moving a writer out of the envelope must not be delegated through an ancestor.
43
- for (let ancestor = path; beneath('/sys/fs/cgroup', ancestor); ancestor = dirname(ancestor))
44
- immutableLimit(ancestor + '/cgroup.procs', system);
45
- if (system.read(path + '/memory.swap.max').trim() !== '0')
46
- return denied('SWAP_LIMIT_REQUIRED');
47
- const memoryBytes = number(system.read(path + '/memory.max')), pids = number(system.read(path + '/pids.max'));
48
- const cpu = system
49
- .read(path + '/cpu.max')
50
- .trim()
51
- .split(/\s+/);
52
- if (cpu.length !== 2)
53
- return denied('CPU_LIMIT_INVALID');
54
- const cpuCores = number(cpu[0]) / number(cpu[1]);
55
- if (memoryBytes < 64 * 1024 * 1024 ||
56
- memoryBytes > (p.role === 'host' ? 512 : 2048) * 1024 * 1024 ||
57
- pids > 128 ||
58
- cpuCores > 2)
59
- return denied('RESOURCE_ENVELOPE_EXCEEDED');
67
+ const envelope = boundedGroup(p, p.cgroup, system);
60
68
  checkProfileMembers(p, system);
61
- return { role: p.role, memoryBytes, pids, cpuCores };
69
+ return envelope;
62
70
  });
63
- // A shared Desktop or another deployment under any profile UID defeats private directory modes.
71
+ // A dedicated background account can use its native user services when root
72
+ // has applied finite limits to that exact systemd user manager.
73
+ const verified = new Set();
64
74
  const processes = system.entries('/proc').filter((x) => /^\d+$/.test(x));
65
75
  if (processes.length > 8192)
66
76
  return denied('PROCESS_SCAN_LIMIT');
@@ -71,8 +81,16 @@ export function kernelProfiles(profiles, system) {
71
81
  if (!profile)
72
82
  continue;
73
83
  processUid(system.read('/proc/' + pid + '/status'), profile.uid);
74
- if (!beneath(profile.cgroup, processGroup(system.read('/proc/' + pid + '/cgroup'))))
84
+ const group = processGroup(system.read('/proc/' + pid + '/cgroup'));
85
+ if (beneath(profile.cgroup, group))
86
+ continue;
87
+ const userServices = '/user.slice/user-' + profile.uid + '.slice/user@' + profile.uid + '.service';
88
+ if (profile.role !== 'background' || !beneath(userServices, group))
75
89
  return denied('ACCOUNT_SHARED_WITH_OTHER_PROCESS');
90
+ if (!verified.has(userServices)) {
91
+ boundedGroup(profile, userServices, system);
92
+ verified.add(userServices);
93
+ }
76
94
  }
77
95
  catch (e) {
78
96
  if (!vanished(e))
@@ -0,0 +1,122 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { linkSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { BotBridgeClient, BotServiceTransport, isBotControlUnavailable, } from "../../vendor/@agent-stack/bridge-client/dist/index.js";
6
+ import { botId, botInteger, botObject } from "../../vendor/@agent-stack/contracts/dist/index.js";
7
+ import { parseProjectHostConfig } from '../../preparation/config.js';
8
+ import { privateDeploymentFile, privateDirectory, deploymentSystem } from '../system.js';
9
+ function projectCall(config, action, args) {
10
+ return new BotBridgeClient(new BotServiceTransport(config.bridgeUrl, 5000), 5000).projectHost(config.project, config.projectCredential, 'preparations', { action, args });
11
+ }
12
+ function renewalReceipt(input, hostId, now) {
13
+ try {
14
+ const receipt = botObject(input, [
15
+ 'schemaVersion',
16
+ 'hostId',
17
+ 'grantId',
18
+ 'renewalRequestId',
19
+ 'expiresAtMs',
20
+ ]);
21
+ if (receipt.schemaVersion === 1 &&
22
+ receipt.hostId === hostId &&
23
+ botInteger(receipt.expiresAtMs, 1) > now)
24
+ return { grantId: botId(receipt.grantId), renewalRequestId: botId(receipt.renewalRequestId) };
25
+ }
26
+ catch {
27
+ // Malformed receipts share one operator-facing error code.
28
+ }
29
+ throw new Error('BOT_LEGACY_PROJECT_RECEIPT_INVALID');
30
+ }
31
+ function projectFailureCode(error) {
32
+ const code = error instanceof Error ? error.message : '';
33
+ switch (code) {
34
+ case 'BOT_LEGACY_PROJECT_RECEIPT_INVALID':
35
+ case 'BOT_LEGACY_PROJECT_AUTHORITY_MISMATCH':
36
+ case 'BOT_LEGACY_PROJECT_RENEWAL_INVALID':
37
+ return code;
38
+ case 'BOT_SERVICE_HTTP_401':
39
+ case 'BOT_SERVICE_HTTP_403':
40
+ return 'BOT_LEGACY_PROJECT_AUTHORIZATION_REQUIRED';
41
+ case 'BOT_SERVICE_HTTP_409':
42
+ return 'BOT_LEGACY_PROJECT_AUTHORITY_CONFLICT';
43
+ default:
44
+ return isBotControlUnavailable(error)
45
+ ? 'BOT_LEGACY_PROJECT_AUTHORITY_UNAVAILABLE'
46
+ : 'BOT_LEGACY_PROJECT_CONFIGURATION_INVALID';
47
+ }
48
+ }
49
+ /** 原授权可用于原位升级。管理员回执只为启用自动续期派生同一 Host 的私有配置。 */
50
+ export async function stageLegacyProject(path, input, now = Date.now(), call = projectCall) {
51
+ const raw = botObject(privateDeploymentFile(path));
52
+ const config = parseProjectHostConfig(raw);
53
+ if (!config || config.deviceLease)
54
+ throw new Error('BOT_LEGACY_PROJECT_INVALID');
55
+ privateDirectory(config.root, deploymentSystem);
56
+ if (input === undefined) {
57
+ // Omitting parallelBots makes this a read of the Host's existing preparations.
58
+ const { preparations } = botObject(await call(config, 'pending', { includeMissions: true }));
59
+ if (!Array.isArray(preparations) ||
60
+ preparations.some((value) => {
61
+ const record = botObject(value);
62
+ return record.hostId !== config.hostId || record.provider !== config.provider;
63
+ }))
64
+ throw new Error('BOT_LEGACY_PROJECT_AUTHORITY_MISMATCH');
65
+ return path;
66
+ }
67
+ const { grantId, renewalRequestId } = renewalReceipt(input, config.hostId, now);
68
+ const renewed = botObject(await call(config, 'renew', { renewalRequestId }));
69
+ if (renewed.schemaVersion !== 1 ||
70
+ renewed.hostId !== config.hostId ||
71
+ renewed.grantId !== grantId ||
72
+ botInteger(renewed.expiresAtMs, 1) <= now)
73
+ throw new Error('BOT_LEGACY_PROJECT_RENEWAL_INVALID');
74
+ if (config.projectLease?.grantId === grantId &&
75
+ config.projectLease?.renewalRequestId === renewalRequestId)
76
+ return path;
77
+ const payload = JSON.stringify({ ...raw, projectLease: { grantId, renewalRequestId } }) + '\n';
78
+ const digest = createHash('sha256').update(payload).digest('hex');
79
+ const target = join(config.root, 'upgrade-' + digest + '.json');
80
+ const staging = mkdtempSync(join(config.root, '.upgrade-'));
81
+ try {
82
+ const staged = join(staging, 'project.json');
83
+ writeFileSync(staged, payload, { flag: 'wx', mode: 0o600 });
84
+ try {
85
+ linkSync(staged, target);
86
+ }
87
+ catch (error) {
88
+ if (error.code !== 'EEXIST')
89
+ throw error;
90
+ privateDeploymentFile(target);
91
+ if (deploymentSystem.read(target) !== payload)
92
+ throw new Error('BOT_LEGACY_PROJECT_STAGE_CONFLICT');
93
+ }
94
+ }
95
+ finally {
96
+ rmSync(staging, { recursive: true });
97
+ }
98
+ return target;
99
+ }
100
+ if (process.platform === 'linux' && process.argv[1] === fileURLToPath(import.meta.url)) {
101
+ try {
102
+ const [config] = process.argv.slice(2);
103
+ if (!config || !process.getuid?.() || !process.geteuid?.())
104
+ throw new Error('BOT_LEGACY_PROJECT_ROLE_REQUIRED');
105
+ // 管理包装器限制管道长度。凭据和原配置只由本服务账号读取。
106
+ const input = readFileSync(0, 'utf8').trim();
107
+ let receipt;
108
+ if (input) {
109
+ try {
110
+ receipt = JSON.parse(input);
111
+ }
112
+ catch {
113
+ throw new Error('BOT_LEGACY_PROJECT_RECEIPT_INVALID');
114
+ }
115
+ }
116
+ process.stdout.write((await stageLegacyProject(config, receipt)) + '\n');
117
+ }
118
+ catch (error) {
119
+ process.stderr.write(projectFailureCode(error) + '\n');
120
+ process.exitCode = 1;
121
+ }
122
+ }
@@ -4,6 +4,7 @@ import { botRuntimeProvider } from "../vendor/@agent-stack/contracts/dist/index.
4
4
  import { botRuntimeBootstrap, botRuntimeBootstrapIdentity } from "../vendor/@agent-stack/runtime-contracts/dist/index.js";
5
5
  import { runtimeEndpoint } from '../adapters/runtime-http/endpoint.js';
6
6
  import { windowsHostState } from '../deployment/windows-state.js';
7
+ import { parseProjectHostConfig } from '../preparation/config.js';
7
8
  const object = (v) => {
8
9
  if (!v || typeof v !== 'object' || Array.isArray(v))
9
10
  throw new Error('BOT_DOCTOR_CONFIG');
@@ -81,13 +82,34 @@ function readinessTarget(config) {
81
82
  ? { readiness: { url, headers: {}, readinessMode: project ? 'project' : 'execution' } }
82
83
  : {};
83
84
  }
84
- /** 仅复用本 Bot 的配置。主管就绪与任务诊断分开,公开探针无需凭据。 */
85
- export function doctorTargets(path, readiness = 'skip', depth = 0) {
85
+ function loadDoctorConfig(path, depth = 0) {
86
86
  if (depth > 1)
87
87
  throw new Error('BOT_DOCTOR_PRIVATE_CONFIG_REQUIRED');
88
88
  const config = object(JSON.parse(privateConfig(path)));
89
89
  if (config.role === 'background' && typeof config.configFile === 'string')
90
- return doctorTargets(config.configFile, readiness, depth + 1);
90
+ return loadDoctorConfig(config.configFile, depth + 1);
91
+ return config;
92
+ }
93
+ /** Only report the saved renewal mode. Bridge remains authoritative about an actual lease. */
94
+ export function doctorRenewal(path) {
95
+ try {
96
+ const config = parseProjectHostConfig(loadDoctorConfig(path));
97
+ if (!config)
98
+ return { state: 'NOT_APPLICABLE' };
99
+ const mode = config.deviceLease
100
+ ? 'DEVICE_LEASE'
101
+ : config.projectLease
102
+ ? 'PROJECT_LEASE'
103
+ : 'MANUAL_PROJECT_GRANT';
104
+ return { state: 'OBSERVED', mode };
105
+ }
106
+ catch {
107
+ return { state: 'UNAVAILABLE', code: 'RENEWAL_CONFIGURATION_UNREADABLE' };
108
+ }
109
+ }
110
+ /** 仅复用本 Bot 的配置。主管就绪与任务诊断分开,公开探针无需凭据。 */
111
+ export function doctorTargets(path, readiness = 'skip') {
112
+ const config = loadDoctorConfig(path);
91
113
  const publicReadiness = readiness === 'skip' ? {} : readinessTarget(config);
92
114
  if (readiness === 'only' && publicReadiness.readiness)
93
115
  return publicReadiness;
@@ -1,3 +1,4 @@
1
+ import { nativeInspectionStatus } from '../recovery/inspection-errors.js';
1
2
  import { doctorProcessFacts } from './process.js';
2
3
  const keys = new Set([
3
4
  'schemaVersion',
@@ -14,6 +15,7 @@ const keys = new Set([
14
15
  'admissionHeld',
15
16
  'stopRequested',
16
17
  'controlReady',
18
+ 'communicationStatus',
17
19
  // 项目主管端口独立于任务子进程,报告接待和准备的实际状态。
18
20
  'deploymentStatus',
19
21
  'receptionStatus',
@@ -155,6 +157,11 @@ export async function doctorProbe(target, path, method = 'GET', fetcher = fetch)
155
157
  const timer = setTimeout(() => abort.abort(), 10_000);
156
158
  timer.unref();
157
159
  let reader;
160
+ let nativeFailure;
161
+ const failure = (status, code = `HTTP_${status}`) => ({
162
+ state: status === 404 ? 'UNSUPPORTED' : 'UNAVAILABLE',
163
+ code,
164
+ });
158
165
  try {
159
166
  const response = await fetcher(new URL(path, target.url), {
160
167
  method,
@@ -170,11 +177,12 @@ export async function doctorProbe(target, path, method = 'GET', fetcher = fetch)
170
177
  const successful = readiness ? response.status === 200 : response.ok;
171
178
  // 主管返回 503 时仍有权威等待状态,不能把它等同于掉线。
172
179
  if (!successful && !(readiness && response.status === 503)) {
173
- await response.body?.cancel().catch(() => { });
174
- return {
175
- state: response.status === 404 ? 'UNSUPPORTED' : 'UNAVAILABLE',
176
- code: `HTTP_${response.status}`,
177
- };
180
+ if (path === '/recovery/native')
181
+ nativeFailure = response.status;
182
+ else {
183
+ await response.body?.cancel().catch(() => { });
184
+ return failure(response.status);
185
+ }
178
186
  }
179
187
  reader = response.body?.getReader();
180
188
  const chunks = [];
@@ -189,6 +197,12 @@ export async function doctorProbe(target, path, method = 'GET', fetcher = fetch)
189
197
  chunks.push(chunk.value);
190
198
  }
191
199
  const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
200
+ if (nativeFailure !== undefined) {
201
+ const code = value?.error;
202
+ return failure(nativeFailure, typeof code === 'string' && nativeInspectionStatus(code) === nativeFailure
203
+ ? code
204
+ : undefined);
205
+ }
192
206
  if (readiness) {
193
207
  const status = readinessFacts(value, successful, target.readinessMode);
194
208
  return status === undefined
@@ -201,6 +215,8 @@ export async function doctorProbe(target, path, method = 'GET', fetcher = fetch)
201
215
  };
202
216
  }
203
217
  catch {
218
+ if (nativeFailure !== undefined && !abort.signal.aborted)
219
+ return failure(nativeFailure);
204
220
  return {
205
221
  state: 'UNAVAILABLE',
206
222
  code: abort.signal.aborted ? 'TIMEOUT' : 'REQUEST_FAILED',
@@ -1,16 +1,21 @@
1
- import { doctorTargets } from './config.js';
1
+ import { doctorRenewal, doctorTargets } from './config.js';
2
2
  import { doctorProbe } from './probe.js';
3
3
  import { botId, botInteger } from "../vendor/@agent-stack/contracts/dist/index.js";
4
4
  // 部分诊断沿原入口直读;未选部分不访问网络,也不冒充已观察。
5
5
  const defaultSections = ['health', 'recovery', 'native', 'connections'];
6
6
  // 进程数值只在明确请求时采集;普通 doctor 不增加请求或默认输出。
7
- const sections = [...defaultSections, 'process', 'readiness'];
7
+ const sections = [...defaultSections, 'process', 'readiness', 'renewal'];
8
8
  /** doctor是可选操作入口;恢复只推动原协调器复查,不清账、不重建Goal、不越过UNKNOWN。 */
9
9
  export async function runBotDoctor(options, fetcher = fetch) {
10
10
  const selected = new Set(options.sections ?? (options.trace ? [] : defaultSections));
11
11
  // 单独读取就绪时不解析控制或 Runtime 凭据,不影响既有诊断的配置合同。
12
- const includeDiagnostics = selected.size > 1 || options.recover || options.refreshConnections || options.trace;
13
- const targets = doctorTargets(options.config, selected.has('readiness') ? (includeDiagnostics ? 'include' : 'only') : 'skip');
12
+ const includeDiagnostics = [...selected].some((section) => section !== 'readiness' && section !== 'renewal') ||
13
+ options.recover ||
14
+ options.refreshConnections ||
15
+ options.trace;
16
+ const targets = includeDiagnostics || selected.has('readiness')
17
+ ? doctorTargets(options.config, selected.has('readiness') ? (includeDiagnostics ? 'include' : 'only') : 'skip')
18
+ : {};
14
19
  const read = (section, target, path) => selected.has(section)
15
20
  ? doctorProbe(target, path, 'GET', fetcher)
16
21
  : Promise.resolve({ state: 'NOT_REQUESTED' });
@@ -43,6 +48,7 @@ export async function runBotDoctor(options, fetcher = fetch) {
43
48
  connections,
44
49
  ...(selected.has('process') ? { process: resources } : {}),
45
50
  ...(selected.has('readiness') ? { readiness } : {}),
51
+ ...(selected.has('renewal') ? { renewal: doctorRenewal(options.config) } : {}),
46
52
  ...(refresh ? { refresh } : {}),
47
53
  ...(recheck ? { recheck } : {}),
48
54
  ...(trace ? { trace } : {}),
@@ -96,6 +102,7 @@ export async function doctorCommand(args) {
96
102
  result.connections,
97
103
  result.process,
98
104
  result.readiness,
105
+ result.renewal,
99
106
  result.refresh,
100
107
  result.recheck,
101
108
  result.trace,
@@ -0,0 +1,78 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { botObject, botText } from "../vendor/@agent-stack/contracts/dist/index.js";
3
+ import { hostEnrollmentOrigin } from './device.js';
4
+ /** 兼容原来没有能力入口的服务。暂时故障和认证错误不降级到密码。 */
5
+ export async function hostSignInMethod(api, request = fetch) {
6
+ const response = await request(new URL('/mobile/auth/methods', hostEnrollmentOrigin(api)), {
7
+ redirect: 'error',
8
+ signal: AbortSignal.timeout(15000),
9
+ });
10
+ if (response.status === 404) {
11
+ await response.body?.cancel();
12
+ return 'password';
13
+ }
14
+ const methods = await read(response);
15
+ if (methods.hostDeviceOidc === true)
16
+ return 'browser';
17
+ if (methods.legacyPassword === true)
18
+ return 'password';
19
+ throw new Error('BOT_DEVICE_LOGIN_UNAVAILABLE');
20
+ }
21
+ /** Host 只展示需在浏览器核对的短码。原设备码在内存和私有 HTTP 请求体中使用。 */
22
+ export async function hostBrowserSession(api, present, request = fetch) {
23
+ const post = async (path, body) => read(await request(new URL(`/mobile/auth/host/${path}`, hostEnrollmentOrigin(api)), {
24
+ method: 'POST',
25
+ redirect: 'error',
26
+ headers: { 'content-type': 'application/json' },
27
+ signal: AbortSignal.timeout(15000),
28
+ body: JSON.stringify(body),
29
+ }));
30
+ const grant = await post('start', {});
31
+ const verification = new URL(botText(grant.verificationUrl, 2048));
32
+ const userCode = botText(grant.userCode, 32);
33
+ const deviceCode = botText(grant.deviceCode, 2048);
34
+ const { expiresIn, interval } = grant;
35
+ if (verification.protocol !== 'https:' ||
36
+ verification.username ||
37
+ verification.password ||
38
+ verification.search ||
39
+ verification.hash ||
40
+ !/^[A-Za-z0-9-]{4,32}$/.test(userCode) ||
41
+ typeof expiresIn !== 'number' ||
42
+ !Number.isInteger(expiresIn) ||
43
+ expiresIn < 1 ||
44
+ expiresIn > 600 ||
45
+ typeof interval !== 'number' ||
46
+ !Number.isInteger(interval) ||
47
+ interval < 5 ||
48
+ interval > 60)
49
+ throw new Error('BOT_DEVICE_LOGIN_RESPONSE_INVALID');
50
+ const deadline = Date.now() + expiresIn * 1000;
51
+ let waitSeconds = interval;
52
+ present({ verificationUrl: verification.href, userCode, expiresIn });
53
+ // 保持 RFC 8628 的最短轮询间隔,遇 slow_down 继续在原截止时间内等待。
54
+ while (Date.now() + waitSeconds * 1000 < deadline) {
55
+ await delay(waitSeconds * 1000);
56
+ const result = await post('poll', { deviceCode });
57
+ if (result.state === 'authorized')
58
+ return botText(botObject(result.session).token, 512);
59
+ if (result.state === 'slow_down')
60
+ waitSeconds += 5;
61
+ else if (result.state !== 'pending')
62
+ throw new Error('BOT_DEVICE_LOGIN_RESPONSE_INVALID');
63
+ }
64
+ throw new Error('BOT_DEVICE_LOGIN_EXPIRED');
65
+ }
66
+ /** 上游异常只显示稳定状态,不把响应正文及其中的授权字段写入诊断。 */
67
+ async function read(response) {
68
+ if (!response.ok) {
69
+ await response.body?.cancel();
70
+ throw new Error(`BOT_DEVICE_LOGIN_HTTP_${response.status}`);
71
+ }
72
+ try {
73
+ return botObject(await response.json());
74
+ }
75
+ catch {
76
+ throw new Error('BOT_DEVICE_LOGIN_RESPONSE_INVALID');
77
+ }
78
+ }