agentxgo 0.1.2-rc.1 → 0.1.2-rc.5

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.
Files changed (141) hide show
  1. package/dist/adapters/runtime-http/client.js +2 -2
  2. package/dist/bootstrap.js +2 -2
  3. package/dist/communication/assembly.js +60 -13
  4. package/dist/communication/calls.js +255 -55
  5. package/dist/communication/config.js +27 -2
  6. package/dist/communication/dispatch-call.js +93 -0
  7. package/dist/communication/media-send.js +186 -0
  8. package/dist/communication/media.js +76 -0
  9. package/dist/communication/original-receipt.js +49 -0
  10. package/dist/communication/pump.js +162 -11
  11. package/dist/communication/resume.js +48 -0
  12. package/dist/communication/task.js +134 -0
  13. package/dist/continuation/coordinator.js +1 -1
  14. package/dist/deployment/components/cli.js +1 -0
  15. package/dist/deployment/failure.js +2 -0
  16. package/dist/deployment/kernel.js +45 -27
  17. package/dist/deployment/linux/legacy-project.js +122 -0
  18. package/dist/doctor/config.js +25 -3
  19. package/dist/doctor/probe.js +21 -5
  20. package/dist/doctor/run.js +11 -4
  21. package/dist/enrollment/browser-login.js +78 -0
  22. package/dist/enrollment/login.js +48 -29
  23. package/dist/enrollment/setup.js +24 -6
  24. package/dist/generated/install-guides.js +4 -4
  25. package/dist/help.js +7 -2
  26. package/dist/lifecycle/http.js +48 -17
  27. package/dist/recovery/coordinator.js +6 -2
  28. package/dist/recovery/inspection-errors.js +19 -0
  29. package/dist/runtime/codex/codex.js +61 -49
  30. package/dist/vendor/@agent-stack/adapter-agentim/dist/account.js +12 -8
  31. package/dist/vendor/@agent-stack/adapter-agentim/dist/direct.js +49 -20
  32. package/dist/vendor/@agent-stack/adapter-agentim/dist/dispatch.js +21 -0
  33. package/dist/vendor/@agent-stack/adapter-agentim/dist/local-inbound.js +117 -0
  34. package/dist/vendor/@agent-stack/adapter-agentim/dist/local-sdk.js +25 -0
  35. package/dist/vendor/@agent-stack/adapter-agentim/dist/local.js +131 -57
  36. package/dist/vendor/@agent-stack/adapter-agentim/dist/scoped-authority.js +167 -0
  37. package/dist/vendor/@agent-stack/adapter-agentim/dist/scoped-rooms.js +109 -0
  38. package/dist/vendor/@agent-stack/adapter-agentim/dist/scoped-sdk.js +206 -0
  39. package/dist/vendor/@agent-stack/adapter-agentim/dist/scoped.js +319 -0
  40. package/dist/vendor/@agent-stack/adapter-agentim/dist/sdk-loader.js +46 -0
  41. package/dist/vendor/@agent-stack/adapter-agentim/package.json +3 -3
  42. package/dist/vendor/@agent-stack/bot-host-journal/dist/communication-calls.js +188 -0
  43. package/dist/vendor/@agent-stack/bot-host-journal/dist/communication-inbound.js +165 -0
  44. package/dist/vendor/@agent-stack/bot-host-journal/dist/communication.js +10 -39
  45. package/dist/vendor/@agent-stack/bridge-client/dist/bot-transport.js +17 -0
  46. package/dist/vendor/@agent-stack/bridge-client/dist/client/bots/client.js +3 -0
  47. package/dist/vendor/@agent-stack/contracts/dist/bots/communication-conversation.js +94 -0
  48. package/dist/vendor/@agent-stack/contracts/dist/bots/communication-native.js +52 -3
  49. package/dist/vendor/@agent-stack/contracts/dist/bots/communication-task.js +150 -0
  50. package/dist/vendor/@agent-stack/contracts/dist/bots/index.js +1 -0
  51. package/dist/vendor/@agent-stack/contracts/dist/bots/interactions.js +8 -1
  52. package/dist/vendor/@agent-stack/contracts/dist/index.js +6 -0
  53. package/dist/vendor/@agent-stack/contracts/dist/public-applications.js +21 -0
  54. package/dist/vendor/@agent-stack/contracts/dist/tenant/actions.js +3 -0
  55. package/dist/vendor/@agent-stack/contracts/dist/tenant/agentim-management.js +285 -0
  56. package/dist/vendor/@agent-stack/contracts/dist/tenant/authorization.js +33 -2
  57. package/dist/vendor/@agent-stack/contracts/dist/tenant/bot-work.js +11 -0
  58. package/dist/vendor/@agent-stack/contracts/dist/tenant/connection-projects.js +33 -0
  59. package/dist/vendor/@agent-stack/contracts/dist/tenant/events.js +33 -19
  60. package/dist/vendor/@agent-stack/contracts/dist/tenant/guidance.js +15 -1
  61. package/dist/vendor/@agent-stack/contracts/dist/tenant/mcp-directory.js +5 -1
  62. package/dist/vendor/@agent-stack/contracts/dist/tenant/native-operations.js +23 -2
  63. package/dist/vendor/@agentims/adapter/dist/delivery/coordinator.js +145 -24
  64. package/dist/vendor/@agentims/adapter/dist/delivery/outbound-authority.js +29 -0
  65. package/dist/vendor/@agentims/adapter/dist/delivery/record.js +12 -0
  66. package/dist/vendor/@agentims/adapter/dist/delivery/reply-error.js +13 -0
  67. package/dist/vendor/@agentims/adapter/dist/errors.js +3 -1
  68. package/dist/vendor/@agentims/adapter/dist/index.js +6 -1
  69. package/dist/vendor/@agentims/adapter/dist/interactions/coordinator.js +276 -0
  70. package/dist/vendor/@agentims/adapter/dist/interactions/http-port.js +78 -0
  71. package/dist/vendor/@agentims/adapter/dist/interactions/record.js +44 -0
  72. package/dist/vendor/@agentims/adapter/dist/interactions/source.js +113 -0
  73. package/dist/vendor/@agentims/adapter/dist/interactions/types.js +1 -0
  74. package/dist/vendor/@agentims/adapter/dist/receipts/original.js +15 -0
  75. package/dist/vendor/@agentims/adapter/dist/receipts/send.js +7 -1
  76. package/dist/vendor/@agentims/adapter/dist/source/event-source.js +21 -2
  77. package/dist/vendor/@agentims/adapter/dist/source/inbound-binding.js +52 -0
  78. package/dist/vendor/@agentims/adapter/dist/source/inbound-reconcile.js +151 -0
  79. package/dist/vendor/@agentims/adapter/dist/source/inbound-subscription.js +81 -0
  80. package/dist/vendor/@agentims/adapter/dist/source/inbound-types.js +1 -0
  81. package/dist/vendor/@agentims/adapter/package.json +2 -2
  82. package/dist/vendor/@agentims/runtime/dist/cli/commands/catalog.js +2 -1
  83. package/dist/vendor/@agentims/runtime/dist/cli/commands/interactions.js +37 -0
  84. package/dist/vendor/@agentims/runtime/dist/cli/help.js +2 -1
  85. package/dist/vendor/@agentims/runtime/dist/index.js +4 -1
  86. package/dist/vendor/@agentims/runtime/package.json +3 -3
  87. package/dist/vendor/@agentims/sdk/dist/api/client.js +13 -0
  88. package/dist/vendor/@agentims/sdk/dist/api/facade.js +6 -0
  89. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/account-operations.js +117 -0
  90. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/authority.js +92 -0
  91. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/budget.js +48 -0
  92. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/catalog.js +168 -0
  93. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/client.js +146 -0
  94. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/conversation-receipt.js +92 -0
  95. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/device-capabilities.js +64 -0
  96. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/dispatch-fence.js +50 -0
  97. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/errors.js +14 -0
  98. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/host-types.js +1 -0
  99. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/index.js +9 -0
  100. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/invitation-directory.js +80 -0
  101. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/media-streams.js +117 -0
  102. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/original-media.js +25 -0
  103. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/original-receipt.js +158 -0
  104. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/receipt-origins.js +141 -0
  105. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/receipt.js +42 -0
  106. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/resources.js +64 -0
  107. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/results.js +32 -0
  108. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/room-directory.js +104 -0
  109. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/scoped-execution.js +105 -0
  110. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/scoped-intent.js +90 -0
  111. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/types.js +3 -0
  112. package/dist/vendor/@agentims/sdk/dist/features/deliveries/client.js +22 -0
  113. package/dist/vendor/@agentims/sdk/dist/features/deliveries/scoped-replies.js +76 -0
  114. package/dist/vendor/@agentims/sdk/dist/features/deliveries/scoped-status.js +36 -0
  115. package/dist/vendor/@agentims/sdk/dist/features/interactions/client.js +49 -0
  116. package/dist/vendor/@agentims/sdk/dist/features/interactions/countdown.js +56 -0
  117. package/dist/vendor/@agentims/sdk/dist/features/interactions/index.js +6 -0
  118. package/dist/vendor/@agentims/sdk/dist/features/interactions/protocol.js +196 -0
  119. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionField.js +73 -0
  120. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionNativeAppearance.js +31 -0
  121. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionNativeContext.js +40 -0
  122. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionQuery.js +44 -0
  123. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionRequest.js +195 -0
  124. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionResponse.js +91 -0
  125. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionStatus.js +151 -0
  126. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionTiming.js +34 -0
  127. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas.js +20 -0
  128. package/dist/vendor/@agentims/sdk/dist/features/interactions/types.js +3 -0
  129. package/dist/vendor/@agentims/sdk/dist/features/interactions/validation.js +111 -0
  130. package/dist/vendor/@agentims/sdk/dist/features/reliability/legacy-outbox.js +1 -0
  131. package/dist/vendor/@agentims/sdk/dist/features/timeline/client.js +1 -1
  132. package/dist/vendor/@agentims/sdk/dist/index.js +5 -0
  133. package/dist/vendor/@agentims/sdk/dist/internal/native/binding.js +42 -1
  134. package/dist/vendor/@agentims/sdk/dist/internal/native/legacy-outbox.js +102 -0
  135. package/dist/vendor/@agentims/sdk/dist/internal/native/transport.js +2 -2
  136. package/dist/vendor/@agentims/sdk/dist/internal/protocol/operations.json +1 -1
  137. package/dist/vendor/@agentims/sdk/dist/internal/transport/client.js +2 -2
  138. package/dist/vendor/@agentims/sdk/dist/internal/transport/request.js +2 -0
  139. package/dist/vendor/@agentims/sdk/package.json +1 -1
  140. package/package.json +2 -2
  141. package/release.json +145 -65
@@ -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 });
package/dist/bootstrap.js CHANGED
@@ -30,7 +30,8 @@ export async function startBotHost(config, startup = {}) {
30
30
  const runtime = new HttpBotRuntimeClient(config.runtimeUrl, config.runtimeToken, config.bridgeCredential, config.runtimeProvider ?? 'codex');
31
31
  const journal = new BotHostJournal(config.journalPath, config.hostId, config.journalCapacity);
32
32
  const coordinator = new BotHostCoordinator(config, bridge, journal, runtime, undefined, ownerPending);
33
- const createCommunication = (setup, authority, botId) => new HostAgentIM(config, journal, coordinator.runtimeSettings, runtime, setup, () => coordinator.communicationContext(), authority, botId);
33
+ const executionWake = new HostWakeHints(config, bridge);
34
+ const createCommunication = (setup, authority, botId) => new HostAgentIM(config, journal, coordinator.runtimeSettings, runtime, setup, () => coordinator.communicationContext(), authority, botId, executionWake.requestRecheck);
34
35
  // 旧配置也可从执行授权发现通信绑定,无需重装或补安装字段。
35
36
  const automaticAgentIM = config.automaticAgentIM ?? !config.agentim;
36
37
  const communication = automaticAgentIM
@@ -51,7 +52,6 @@ export async function startBotHost(config, startup = {}) {
51
52
  return client;
52
53
  });
53
54
  const execution = new HostComponentStatus('host.execution');
54
- const executionWake = new HostWakeHints(config, bridge);
55
55
  const observeExecution = () => {
56
56
  const progress = coordinator.componentProgress;
57
57
  if (progress.syncAtMs !== undefined)
@@ -67,23 +67,30 @@ 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
- if (active?.executionId === executionId && sameBinding(active.grant, grant)) {
85
- active.grant = grant;
88
+ if (active?.executionId === executionId && sameReceiver(active.grant, grant)) {
86
89
  try {
90
+ if (canonicalBotJson(active.grant.outbound ?? null) !==
91
+ canonicalBotJson(grant.outbound ?? null))
92
+ active.pump.updateOutbound(grant.outbound);
93
+ active.grant = grant;
87
94
  await this.checkDevice(active.account.client, binding, { timeoutMs: 3000 });
88
95
  return;
89
96
  }
@@ -117,7 +124,7 @@ export class HostAgentIMAssembly {
117
124
  }
118
125
  try {
119
126
  const authority = () => {
120
- if (!this.channel || !this.authorized(this.channel))
127
+ if (!this.channel || this.channel !== channel || !this.authorized(channel))
121
128
  throw new Error('AGENTIM_BINDING_UNAVAILABLE');
122
129
  };
123
130
  const pump = this.create({
@@ -125,8 +132,49 @@ export class HostAgentIMAssembly {
125
132
  binding,
126
133
  initialCheckpoint: account.checkpoint,
127
134
  runtimeActors: old?.runtimeActors ?? [],
135
+ ...(grant.outbound === undefined ? {} : { outboundGrant: grant.outbound }),
136
+ ...(grant.accountMode === undefined ? {} : { accountMode: grant.accountMode }),
137
+ ...(grant.inboundRules &&
138
+ grant.inboundRevision !== undefined && {
139
+ inbound: {
140
+ rules: grant.inboundRules,
141
+ revision: grant.inboundRevision,
142
+ check: async (signal) => {
143
+ signal.throwIfAborted();
144
+ authority();
145
+ const current = await this.bridge.nativeAgentIMBinding(project, executionId, bridgeCredential);
146
+ authority();
147
+ signal.throwIfAborted();
148
+ if (!current ||
149
+ current.revoked ||
150
+ current.expiresAtMs <= Date.now() ||
151
+ !sameReceiver(channel.grant, current))
152
+ throw new Error('AGENTIM_INBOUND_AUTHORITY_CHANGED');
153
+ },
154
+ },
155
+ }),
156
+ ...(this.bridge.agentIMTask && {
157
+ taskAuthority: async (request, signal) => {
158
+ authority();
159
+ const reply = await this.bridge.agentIMTask(project, executionId, bridgeCredential, request, signal);
160
+ authority();
161
+ return reply;
162
+ },
163
+ }),
164
+ checkOutbound: async (outbound) => {
165
+ authority();
166
+ const current = await this.bridge.nativeAgentIMBinding(project, executionId, bridgeCredential);
167
+ authority();
168
+ if (!current ||
169
+ current.revoked ||
170
+ current.expiresAtMs <= Date.now() ||
171
+ !sameReceiver(channel.grant, current) ||
172
+ canonicalBotJson(current.outbound ?? null) !== canonicalBotJson(outbound ?? null))
173
+ throw new Error('AGENTIM_OUTBOUND_AUTHORITY_CHANGED');
174
+ },
128
175
  }, authority, botId);
129
- this.channel = { executionId, grant, account, pump };
176
+ const channel = { executionId, grant, account, pump };
177
+ this.channel = channel;
130
178
  pump.start();
131
179
  }
132
180
  catch (error) {
@@ -164,9 +212,8 @@ export class HostAgentIMAssembly {
164
212
  await this.disconnect();
165
213
  }
166
214
  }
167
- /** 续期更新原租约,不重置设备、房间或已知输入。 */
168
- function sameBinding(a, b) {
169
- const { expiresAtMs: _untilA, ...identityA } = a;
170
- const { expiresAtMs: _untilB, ...identityB } = b;
171
- return canonicalBotJson(identityA) === canonicalBotJson(identityB);
215
+ /** 续期和出站委托可独立变化;其余绑定事实继续决定接收器身份。 */
216
+ function sameReceiver(a, b) {
217
+ return (canonicalBotJson({ ...a, expiresAtMs: b.expiresAtMs, outbound: null }) ===
218
+ canonicalBotJson({ ...b, outbound: null }));
172
219
  }
@@ -1,20 +1,61 @@
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";
1
+ import { callDirectAgentIM, directAgentIMDigest, directAgentIMCatalogue, directAgentIMOperation, directAgentIMSchema, directAgentIMInput, communicationReplyReceipt, scopedAgentIMFailure, } from "../vendor/@agent-stack/adapter-agentim/dist/local.js";
2
+ import { BotContractError, botObject, botId, botInteger, botText } from "../vendor/@agent-stack/contracts/dist/index.js";
3
+ import { agentIMDeviceRef, resumeAgentIMCall } from './resume.js';
4
+ import { receiveAgentIMAttachment } from './media.js';
5
+ import { AgentIMTaskAuthority } from './task.js';
6
+ import { AgentIMAttachmentDelivery, prepareAgentIMAttachment } from './media-send.js';
7
+ import { readOriginalAgentIM } from './original-receipt.js';
8
+ import { dispatchAgentIMCall } from './dispatch-call.js';
9
+ const needsTurnInputs = Symbol('native input context before dispatch');
10
+ function preflightFailure(error, signal) {
11
+ const result = scopedAgentIMFailure(signal?.aborted ? signal.reason : error);
12
+ return result.code === 'AGENTIM_OUTBOUND_ROOM_DENIED' ||
13
+ result.code === 'AGENTIM_JOINED_ROOMS_UNAVAILABLE' ||
14
+ result.code === 'AGENTIM_ACCOUNT_RECIPIENT_SCOPE_REQUIRED'
15
+ ? { ...result, [needsTurnInputs]: true }
16
+ : result;
17
+ }
18
+ export function agentIMNeedsTurnInputs(result) {
19
+ if (!result || typeof result !== 'object')
20
+ return false;
21
+ const { reply, delivery } = result;
22
+ return [result, reply, delivery].some((value) => !!value && typeof value === 'object' && needsTurnInputs in value);
23
+ }
3
24
  /** SDK 拥有业务权限和效果;Host 仅持原写调用摘要/结果,未知写绝不换身份重发。 */
4
25
  export class AgentIMCalls {
5
26
  config;
6
27
  journal;
7
28
  key;
29
+ scoped;
30
+ mediaDirectory;
31
+ tasks;
8
32
  active = new Map();
33
+ scopeLifetime = new AbortController();
34
+ device;
35
+ attachments;
9
36
  closed = false;
10
- constructor(config, journal, key) {
37
+ constructor(config, journal, key, scoped = undefined, mediaDirectory, tasks) {
11
38
  this.config = config;
12
39
  this.journal = journal;
13
40
  this.key = key;
41
+ this.scoped = scoped;
42
+ this.mediaDirectory = mediaDirectory;
43
+ this.tasks = tasks;
44
+ this.device = agentIMDeviceRef(config.binding.identity);
45
+ if (tasks?.available)
46
+ this.attachments = new AgentIMAttachmentDelivery(tasks, journal.communication, key, this.device);
47
+ }
48
+ updateScope(scoped) {
49
+ const previous = this.scopeLifetime;
50
+ this.scoped = scoped;
51
+ this.scopeLifetime = new AbortController();
52
+ previous.abort(new Error('AGENTIM_OUTBOUND_AUTHORITY_CHANGED'));
14
53
  }
15
- handle(raw, signal) {
54
+ handle(raw, callerSignal) {
16
55
  if (this.closed)
17
56
  return Promise.reject(new Error('AGENTIM_CONNECTION_CLOSED'));
57
+ const lifetime = this.scopeLifetime.signal;
58
+ const signal = callerSignal ? AbortSignal.any([lifetime, callerSignal]) : lifetime;
18
59
  const request = botObject(raw, [
19
60
  'operation',
20
61
  'operationId',
@@ -23,85 +64,244 @@ export class AgentIMCalls {
23
64
  'inputRequestId',
24
65
  'offset',
25
66
  'sdkRequestId',
67
+ 'nativeInputs',
68
+ 'originalRequestId',
26
69
  ]);
70
+ // 私有 Runtime 从实际呈现的用户项提供原输入 ID;房间只从本绑定的收件账本取。
71
+ let scoped = this.scoped;
72
+ if (scoped && request.nativeInputs !== undefined) {
73
+ if (!Array.isArray(request.nativeInputs))
74
+ throw new Error('AGENTIM_NATIVE_INPUT_INVALID');
75
+ const rooms = new Set();
76
+ const peers = new Set();
77
+ for (const raw of request.nativeInputs) {
78
+ const source = botObject(raw, ['requestId', 'nativeRef']);
79
+ const ref = botText(source.nativeRef);
80
+ const original = this.journal.communication.inputReceipt(this.key, botId(source.requestId), true);
81
+ // Native 已呈现的首个工具可先于 SAVED 回包;若已有回证,必须是同一原生项。
82
+ if (original && (original.nativeRef === null || original.nativeRef === ref))
83
+ rooms.add(original.roomId);
84
+ if (original?.nativeRef === ref && original.sender)
85
+ peers.add(original.sender);
86
+ }
87
+ scoped = peers.size
88
+ ? scoped.withInputRooms([...rooms], [...peers])
89
+ : scoped.withInputRooms([...rooms]);
90
+ }
27
91
  if (request.operation === 'discover')
28
- return Promise.resolve(directAgentIMCatalogue());
92
+ return this.scoped
93
+ ? this.scoped
94
+ .discover(request.input, signal)
95
+ .catch((error) => scopedAgentIMFailure(error))
96
+ : Promise.resolve(directAgentIMCatalogue());
29
97
  if (request.operation === 'input')
30
- return Promise.resolve(this.journal.communication.readInput(this.key, botId(request.inputRequestId), botInteger(request.offset ?? 0)) ?? {
31
- state: 'NOT_FOUND',
32
- });
98
+ return this.readInput(botId(request.inputRequestId), botInteger(request.offset ?? 0), signal);
33
99
  if (request.operation === 'receipt') {
100
+ if (request.input !== undefined || request.originalRequestId !== undefined) {
101
+ if (request.inputRequestId !== undefined ||
102
+ request.sdkRequestId !== undefined ||
103
+ (request.input !== undefined && request.originalRequestId !== undefined))
104
+ throw new BotContractError('original receipt reference must be unique');
105
+ return readOriginalAgentIM({
106
+ scoped,
107
+ attachments: this.attachments,
108
+ journal: this.journal.communication,
109
+ key: this.key,
110
+ device: this.device,
111
+ request,
112
+ signal,
113
+ }).catch((error) => {
114
+ const failure = preflightFailure(error);
115
+ return {
116
+ state: 'UNAVAILABLE',
117
+ code: failure.code,
118
+ recovery: 'query_original',
119
+ ...(needsTurnInputs in failure && { [needsTurnInputs]: true }),
120
+ };
121
+ });
122
+ }
34
123
  const original = this.journal.communication.inputReceipt(this.key, botId(request.inputRequestId));
35
124
  if (!original)
36
125
  return Promise.resolve({ state: 'NOT_FOUND' });
37
126
  if (request.sdkRequestId === undefined)
38
127
  return Promise.resolve({ input: original });
39
- return communicationReplyReceipt(this.config, original, request.sdkRequestId, signal ? { signal } : {}).then((reply) => ({ input: original, reply }));
128
+ const reply = scoped
129
+ ? Promise.resolve()
130
+ .then(() => scoped.replyReceipt(original, request.sdkRequestId, signal))
131
+ .catch((error) => preflightFailure(error))
132
+ : communicationReplyReceipt(this.config, original, request.sdkRequestId, { signal });
133
+ return reply.then((result) => ({ input: original, reply: result }));
134
+ }
135
+ if (request.operation === 'receiveMedia') {
136
+ if (!scoped || !this.mediaDirectory)
137
+ return Promise.resolve({ state: 'UNAVAILABLE', code: 'AGENTIM_MEDIA_UNAVAILABLE' });
138
+ return receiveAgentIMAttachment({
139
+ scoped,
140
+ body: request.input,
141
+ device: this.device,
142
+ directory: this.mediaDirectory,
143
+ signal,
144
+ }).catch(preflightFailure);
145
+ }
146
+ if (request.operation === 'taskProposal' || request.operation === 'taskDecision') {
147
+ if (!scoped || !this.tasks?.available)
148
+ return Promise.resolve({
149
+ state: 'UNAVAILABLE',
150
+ code: 'AGENTIM_TASK_AUTHORITY_UNAVAILABLE',
151
+ });
152
+ if (request.operation === 'taskDecision')
153
+ return this.tasks.call('task-status', request.input, signal).catch(preflightFailure);
154
+ return this.proposeTask(scoped, this.tasks, request.input, botId(request.requestId), signal).catch(preflightFailure);
155
+ }
156
+ if (request.operation === 'sendMedia') {
157
+ if (!scoped || !this.attachments)
158
+ return Promise.resolve({
159
+ state: 'UNAVAILABLE',
160
+ code: 'AGENTIM_TASK_AUTHORITY_UNAVAILABLE',
161
+ });
162
+ const input = botObject(request.input, ['interactionId', 'resume']);
163
+ const interactionId = botId(input.interactionId);
164
+ const resumeId = input.resume === true ? botId(request.requestId) : undefined;
165
+ return this.track('attachment:' + interactionId, 'attachment', () => this.attachments.send(scoped, interactionId, resumeId, signal).catch(preflightFailure));
166
+ }
167
+ if (request.operation === 'resume') {
168
+ if (!scoped)
169
+ return Promise.resolve({ state: 'UNAVAILABLE', code: 'AGENTIM_RESUME_UNAVAILABLE' });
170
+ const requestId = botId(request.requestId);
171
+ const originalRequestId = botText(request.originalRequestId, 128);
172
+ const input = botObject(request.input);
173
+ const digest = directAgentIMDigest('resume', { body: { originalRequestId, input } });
174
+ return this.track('resume:' + requestId, digest, () => resumeAgentIMCall({
175
+ scoped,
176
+ journal: this.journal.communication,
177
+ key: this.key,
178
+ device: this.device,
179
+ requestId,
180
+ originalRequestId,
181
+ input,
182
+ signal,
183
+ }).catch(preflightFailure));
184
+ }
185
+ if (request.operation !== 'schema' && request.operation !== 'call')
186
+ return Promise.reject(new Error('AGENTIM_OPERATION_INVALID'));
187
+ let operationId;
188
+ try {
189
+ operationId = botId(request.operationId);
190
+ }
191
+ catch (error) {
192
+ if (!(error instanceof BotContractError))
193
+ throw error;
194
+ return Promise.resolve({
195
+ state: 'REJECTED',
196
+ disposition: 'NOT_SENT',
197
+ code: 'AGENTIM_OPERATION_ID_REQUIRED',
198
+ field: 'operationId',
199
+ hint: 'Pass the SDK operationId at the top level. The SDK schema describes only input.',
200
+ });
201
+ }
202
+ if (scoped) {
203
+ if (request.operation === 'schema') {
204
+ const details = request.input === undefined
205
+ ? false
206
+ : botObject(request.input, ['details']).details === true;
207
+ return scoped
208
+ .schema(operationId, details)
209
+ .catch((error) => scopedAgentIMFailure(error));
210
+ }
211
+ return this.callScoped(scoped, operationId, botId(request.requestId), request.input, signal);
40
212
  }
41
- const operationId = botId(request.operationId);
42
213
  if (request.operation === 'schema')
43
214
  return Promise.resolve(directAgentIMSchema(operationId));
44
- if (request.operation !== 'call')
45
- return Promise.reject(new Error('AGENTIM_OPERATION_INVALID'));
46
215
  const operation = directAgentIMOperation(operationId), id = botId(request.requestId);
47
216
  const input = directAgentIMInput(operationId, request.input, id);
48
- const digest = directAgentIMDigest(operationId, input);
49
217
  const body = input.body;
50
218
  const sdkRequestId = typeof body?.request_id === 'string' ? body.request_id : undefined;
51
- // AS 调用 ID 与 SDK request_id 可以不同;未知写仍必须给出真实上游回查定位。
52
- const annotate = (value) => value && typeof value === 'object' && 'state' in value && value.state === 'UNKNOWN'
53
- ? { ...value, operationId, ...(sdkRequestId ? { sdkRequestId } : {}) }
54
- : value;
219
+ return dispatchAgentIMCall(this.dispatchContext(), {
220
+ id,
221
+ operationId,
222
+ effect: operation.effect,
223
+ digest: directAgentIMDigest(operationId, input),
224
+ sdkRequestId,
225
+ }, (signal, beforeInvoke) => callDirectAgentIM(this.config, operationId, input, beforeInvoke, { signal }), signal);
226
+ }
227
+ async proposeTask(scoped, tasks, raw, requestId, signal) {
228
+ const { roomId, intent } = botObject(raw).kind === 'attachment'
229
+ ? await prepareAgentIMAttachment(scoped, raw, this.device, signal)
230
+ : AgentIMTaskAuthority.proposal(raw);
231
+ return tasks.propose(scoped, roomId, requestId, intent, (channel, id, input) => this.callScoped(channel, 'enqueueText', id, input, signal), signal);
232
+ }
233
+ async readInput(id, offset, signal) {
234
+ const saved = this.journal.communication.readInput(this.key, id, offset);
235
+ if (!saved)
236
+ return { state: 'NOT_FOUND' };
237
+ const { inboundRevision, ...input } = saved.input;
238
+ if (inboundRevision !== undefined) {
239
+ const inbound = this.config.inbound;
240
+ if (inbound?.revision !== inboundRevision ||
241
+ !inbound?.rules.some(({ roomId }) => roomId === input.roomId))
242
+ return { state: 'UNAVAILABLE', code: 'AGENTIM_INBOUND_AUTHORITY_CHANGED' };
243
+ try {
244
+ await inbound.check(signal);
245
+ }
246
+ catch (error) {
247
+ return scopedAgentIMFailure(error);
248
+ }
249
+ }
250
+ return { ...saved, input };
251
+ }
252
+ async callScoped(scoped, operationId, id, raw, signal) {
253
+ try {
254
+ const prepared = await scoped
255
+ .prepare(operationId, raw, id, signal)
256
+ .catch((error) => preflightFailure(error, signal));
257
+ if (!('input' in prepared))
258
+ return prepared;
259
+ const { input, effect, roomId, userId, sdkRequestId, sdkTxnId, roomName, mandateId } = prepared;
260
+ if (this.closed)
261
+ throw new Error('AGENTIM_CONNECTION_CLOSED');
262
+ signal.throwIfAborted();
263
+ return await dispatchAgentIMCall(this.dispatchContext(), {
264
+ id,
265
+ operationId,
266
+ effect,
267
+ digest: directAgentIMDigest(operationId, input),
268
+ sdkRequestId,
269
+ ...(sdkTxnId === undefined ? {} : { sdkTxnId }),
270
+ ...(roomId === undefined ? {} : { roomId }),
271
+ ...(userId === undefined ? {} : { userId }),
272
+ ...(roomName === undefined ? {} : { roomName }),
273
+ ...(mandateId === undefined ? {} : { mandateId }),
274
+ scoped: true,
275
+ }, (signal, beforeInvoke) => scoped.call(operationId, input, signal, beforeInvoke, roomId, undefined, mandateId), signal);
276
+ }
277
+ catch (error) {
278
+ return scopedAgentIMFailure(error);
279
+ }
280
+ }
281
+ dispatchContext() {
282
+ return {
283
+ journal: this.journal.communication,
284
+ key: this.key,
285
+ device: this.device,
286
+ track: this.track.bind(this),
287
+ };
288
+ }
289
+ track(id, digest, run) {
55
290
  const previous = this.active.get(id);
56
291
  if (previous)
57
292
  return previous.digest === digest
58
293
  ? previous.result
59
294
  : Promise.reject(new Error('AGENTIM_CALL_CONFLICT'));
60
- const stop = new AbortController();
61
- const cancelled = AbortSignal.any([stop.signal, ...(signal ? [signal] : [])]);
62
295
  const work = Promise.resolve()
63
- .then(async () => {
64
- if (operation.effect === 'read')
65
- return callDirectAgentIM(this.config, operationId, input, undefined, {
66
- signal: cancelled,
67
- }).catch(directAgentIMFailure);
68
- const saved = this.journal.communication.lookupCall(this.key, id, digest);
69
- if (saved)
70
- return annotate(saved.value);
71
- let value, recorded = false;
72
- try {
73
- value = await callDirectAgentIM(this.config, operationId, input, () => {
74
- const prior = this.journal.communication.reserveCall(this.key, id, digest);
75
- recorded = !prior;
76
- return prior;
77
- }, { signal: cancelled });
78
- }
79
- catch (error) {
80
- // 身份查询期间取消尚未派发;真正intent之后取消仍保存原UNKNOWN,不能重发。
81
- value =
82
- !recorded && cancelled.aborted
83
- ? {
84
- state: 'REJECTED',
85
- disposition: 'NOT_SENT',
86
- code: 'AGENTIM_CALL_CANCELLED',
87
- requestId: id,
88
- operationId,
89
- }
90
- : annotate({ ...directAgentIMFailure(error), requestId: id, operationId });
91
- }
92
- if (recorded)
93
- this.journal.communication.callResult(this.key, id, value);
94
- return value;
95
- })
296
+ .then(run)
96
297
  .finally(() => this.active.delete(id));
97
- this.active.set(id, { digest, result: work, stop });
298
+ this.active.set(id, { digest, result: work });
98
299
  return work;
99
300
  }
100
301
  /** 只排空本连接操作,关闭不注销账号或停止官方 daemon。 */
101
302
  async close() {
102
303
  this.closed = true;
103
- for (const call of this.active.values())
104
- call.stop.abort();
304
+ this.scopeLifetime.abort(new Error('AGENTIM_BINDING_UNAVAILABLE'));
105
305
  await Promise.allSettled([...this.active.values()].map((value) => value.result));
106
306
  }
107
307
  }
@@ -1,7 +1,14 @@
1
1
  import { isAbsolute } from 'node:path';
2
- import { agentIMIdentity, botId, botInteger, botObject, botText } from "../vendor/@agent-stack/contracts/dist/index.js";
2
+ import { agentIMIdentity, botId, botInteger, botObject, botText, parseBotNativeAgentIMOutbound, } from "../vendor/@agent-stack/contracts/dist/index.js";
3
3
  export function hostAgentIMConfig(raw) {
4
- const v = botObject(raw, ['connectionFile', 'initialCheckpoint', 'binding', 'runtimeActors']);
4
+ const v = botObject(raw, [
5
+ 'connectionFile',
6
+ 'initialCheckpoint',
7
+ 'binding',
8
+ 'runtimeActors',
9
+ 'sdkRoot',
10
+ 'outbound',
11
+ ]);
5
12
  const connectionFile = botText(v.connectionFile);
6
13
  if (!isAbsolute(connectionFile))
7
14
  throw new Error('BOT_AGENTIM_PRIVATE_CONNECTION_REQUIRED');
@@ -9,8 +16,25 @@ export function hostAgentIMConfig(raw) {
9
16
  const i = botObject(b.identity, ['homeserver', 'user_id', 'device_id']);
10
17
  if (!Array.isArray(b.rooms) || !Array.isArray(v.runtimeActors))
11
18
  throw new Error('BOT_AGENTIM_BINDING_INVALID');
19
+ let outbound;
20
+ const sdkRoot = v.sdkRoot === undefined ? undefined : botText(v.sdkRoot);
21
+ if (sdkRoot && !isAbsolute(sdkRoot))
22
+ throw new Error('AGENTIM_SDK_ROOT_REQUIRED');
23
+ if (v.outbound !== undefined) {
24
+ const { sdkRoot: configuredRoot, ...value } = botObject(v.outbound);
25
+ const sdkRoot = configuredRoot === undefined ? undefined : botText(configuredRoot);
26
+ if (sdkRoot && !isAbsolute(sdkRoot))
27
+ throw new Error('AGENTIM_SDK_ROOT_REQUIRED');
28
+ const scope = Object.hasOwn(value, 'roomId')
29
+ ? { roomId: agentIMIdentity(botObject(value, ['roomId']).roomId, '!') }
30
+ : parseBotNativeAgentIMOutbound(value);
31
+ if ('mode' in scope)
32
+ throw new Error('BOT_AGENTIM_ACCOUNT_MODE_REQUIRES_NATIVE_GRANT');
33
+ outbound = { ...scope, ...(sdkRoot ? { sdkRoot } : {}) };
34
+ }
12
35
  return {
13
36
  connectionFile,
37
+ ...(sdkRoot ? { sdkRoot } : {}),
14
38
  initialCheckpoint: botText(v.initialCheckpoint),
15
39
  binding: {
16
40
  bindingId: botId(b.bindingId),
@@ -29,5 +53,6 @@ export function hostAgentIMConfig(raw) {
29
53
  principal: { issuer: botText(principal.issuer), subject: botText(principal.subject) },
30
54
  };
31
55
  }),
56
+ ...(outbound ? { outbound } : {}),
32
57
  };
33
58
  }
@@ -0,0 +1,93 @@
1
+ import { directAgentIMFailure, scopedAgentIMFailure, } from "../vendor/@agent-stack/adapter-agentim/dist/local.js";
2
+ import { agentIMResultState } from './resume.js';
3
+ export function dispatchAgentIMCall(context, prepared, invoke, cancelled) {
4
+ const { id, operationId, effect, digest, sdkRequestId, sdkTxnId, roomId, userId, roomName, mandateId, scoped, } = prepared;
5
+ // AS 调用 ID 与 SDK request_id 可以不同;未知写仍必须给出真实上游回查定位。
6
+ let receiptId = sdkRequestId;
7
+ const annotate = (value) => {
8
+ const state = agentIMResultState(value);
9
+ if (typeof state !== 'string' || state === 'sent' || state === 'succeeded')
10
+ return value;
11
+ if (state !== 'UNKNOWN' && !scoped)
12
+ return value;
13
+ const original = value;
14
+ return {
15
+ ...value,
16
+ operationId,
17
+ ...(scoped
18
+ ? { originalRequestId: original.originalRequestId ?? original.requestId ?? id }
19
+ : {}),
20
+ ...(receiptId ? { sdkRequestId: receiptId } : {}),
21
+ ...(sdkTxnId ? { sdkTxnId } : {}),
22
+ };
23
+ };
24
+ return context.track(id, digest, async () => {
25
+ if (cancelled.aborted)
26
+ return {
27
+ state: 'REJECTED',
28
+ disposition: 'NOT_SENT',
29
+ code: 'AGENTIM_CALL_CANCELLED',
30
+ requestId: id,
31
+ operationId,
32
+ };
33
+ if (effect !== 'write')
34
+ return invoke(cancelled).catch((error) => scoped ? scopedAgentIMFailure(error) : directAgentIMFailure(error));
35
+ const saved = scoped ? null : context.journal.lookupCall(context.key, id, digest);
36
+ if (saved)
37
+ return annotate(saved.value);
38
+ let value, recorded = false;
39
+ try {
40
+ value = await invoke(cancelled, () => {
41
+ const origin = scoped
42
+ ? {
43
+ ...(sdkRequestId === undefined ? {} : { sdkRequestId }),
44
+ ...(sdkTxnId === undefined ? {} : { transactionId: sdkTxnId }),
45
+ operationId,
46
+ ...(roomId === undefined ? {} : { roomId }),
47
+ ...(userId === undefined ? {} : { userId }),
48
+ ...(roomName === undefined ? {} : { roomName }),
49
+ ...(mandateId === undefined ? {} : { mandateId }),
50
+ device: context.device,
51
+ }
52
+ : undefined;
53
+ const prior = context.journal.reserveCall(context.key, id, digest, origin);
54
+ recorded = !prior;
55
+ return prior;
56
+ });
57
+ if (scoped)
58
+ value = annotate(value);
59
+ }
60
+ catch (error) {
61
+ if (scoped) {
62
+ const failure = scopedAgentIMFailure(error, recorded);
63
+ if (recorded && failure.disposition === 'NOT_SENT') {
64
+ context.journal.releaseUnsentCall(context.key, id, digest);
65
+ return { ...failure, requestId: id, operationId };
66
+ }
67
+ if (receiptId === undefined &&
68
+ error instanceof Error &&
69
+ error.name === 'AgentOperationError' &&
70
+ 'requestId' in error &&
71
+ typeof error.requestId === 'string')
72
+ receiptId = error.requestId;
73
+ value = annotate({ ...failure, requestId: id, operationId });
74
+ }
75
+ else {
76
+ // 身份查询期间取消尚未派发;真正intent之后取消仍保存原UNKNOWN,不能重发。
77
+ value =
78
+ !recorded && cancelled.aborted
79
+ ? {
80
+ state: 'REJECTED',
81
+ disposition: 'NOT_SENT',
82
+ code: 'AGENTIM_CALL_CANCELLED',
83
+ requestId: id,
84
+ operationId,
85
+ }
86
+ : annotate({ ...directAgentIMFailure(error), requestId: id, operationId });
87
+ }
88
+ }
89
+ if (recorded)
90
+ context.journal.callResult(context.key, id, value, receiptId);
91
+ return value;
92
+ });
93
+ }