agentxgo 0.1.2-rc.4 → 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 (126) hide show
  1. package/dist/bootstrap.js +2 -2
  2. package/dist/communication/assembly.js +52 -7
  3. package/dist/communication/calls.js +238 -52
  4. package/dist/communication/config.js +27 -2
  5. package/dist/communication/dispatch-call.js +93 -0
  6. package/dist/communication/media-send.js +186 -0
  7. package/dist/communication/media.js +76 -0
  8. package/dist/communication/original-receipt.js +49 -0
  9. package/dist/communication/pump.js +162 -11
  10. package/dist/communication/resume.js +48 -0
  11. package/dist/communication/task.js +134 -0
  12. package/dist/generated/install-guides.js +2 -2
  13. package/dist/help.js +1 -1
  14. package/dist/lifecycle/http.js +10 -2
  15. package/dist/runtime/codex/codex.js +61 -49
  16. package/dist/vendor/@agent-stack/adapter-agentim/dist/account.js +12 -8
  17. package/dist/vendor/@agent-stack/adapter-agentim/dist/direct.js +49 -20
  18. package/dist/vendor/@agent-stack/adapter-agentim/dist/dispatch.js +21 -0
  19. package/dist/vendor/@agent-stack/adapter-agentim/dist/local-inbound.js +117 -0
  20. package/dist/vendor/@agent-stack/adapter-agentim/dist/local-sdk.js +25 -0
  21. package/dist/vendor/@agent-stack/adapter-agentim/dist/local.js +131 -57
  22. package/dist/vendor/@agent-stack/adapter-agentim/dist/scoped-authority.js +167 -0
  23. package/dist/vendor/@agent-stack/adapter-agentim/dist/scoped-rooms.js +109 -0
  24. package/dist/vendor/@agent-stack/adapter-agentim/dist/scoped-sdk.js +206 -0
  25. package/dist/vendor/@agent-stack/adapter-agentim/dist/scoped.js +319 -0
  26. package/dist/vendor/@agent-stack/adapter-agentim/dist/sdk-loader.js +46 -0
  27. package/dist/vendor/@agent-stack/adapter-agentim/package.json +3 -3
  28. package/dist/vendor/@agent-stack/bot-host-journal/dist/communication-calls.js +188 -0
  29. package/dist/vendor/@agent-stack/bot-host-journal/dist/communication-inbound.js +165 -0
  30. package/dist/vendor/@agent-stack/bot-host-journal/dist/communication.js +10 -39
  31. package/dist/vendor/@agent-stack/bridge-client/dist/bot-transport.js +12 -0
  32. package/dist/vendor/@agent-stack/bridge-client/dist/client/bots/client.js +3 -0
  33. package/dist/vendor/@agent-stack/contracts/dist/bots/communication-conversation.js +94 -0
  34. package/dist/vendor/@agent-stack/contracts/dist/bots/communication-native.js +52 -3
  35. package/dist/vendor/@agent-stack/contracts/dist/bots/communication-task.js +150 -0
  36. package/dist/vendor/@agent-stack/contracts/dist/bots/index.js +1 -0
  37. package/dist/vendor/@agent-stack/contracts/dist/bots/interactions.js +8 -1
  38. package/dist/vendor/@agent-stack/contracts/dist/index.js +4 -0
  39. package/dist/vendor/@agent-stack/contracts/dist/tenant/actions.js +3 -0
  40. package/dist/vendor/@agent-stack/contracts/dist/tenant/agentim-management.js +285 -0
  41. package/dist/vendor/@agent-stack/contracts/dist/tenant/authorization.js +33 -2
  42. package/dist/vendor/@agent-stack/contracts/dist/tenant/bot-work.js +11 -0
  43. package/dist/vendor/@agent-stack/contracts/dist/tenant/connection-projects.js +33 -0
  44. package/dist/vendor/@agent-stack/contracts/dist/tenant/events.js +33 -19
  45. package/dist/vendor/@agent-stack/contracts/dist/tenant/guidance.js +15 -1
  46. package/dist/vendor/@agent-stack/contracts/dist/tenant/mcp-directory.js +5 -1
  47. package/dist/vendor/@agent-stack/contracts/dist/tenant/native-operations.js +23 -2
  48. package/dist/vendor/@agentims/adapter/dist/delivery/coordinator.js +145 -24
  49. package/dist/vendor/@agentims/adapter/dist/delivery/outbound-authority.js +29 -0
  50. package/dist/vendor/@agentims/adapter/dist/delivery/record.js +12 -0
  51. package/dist/vendor/@agentims/adapter/dist/delivery/reply-error.js +13 -0
  52. package/dist/vendor/@agentims/adapter/dist/errors.js +3 -1
  53. package/dist/vendor/@agentims/adapter/dist/index.js +6 -1
  54. package/dist/vendor/@agentims/adapter/dist/interactions/coordinator.js +276 -0
  55. package/dist/vendor/@agentims/adapter/dist/interactions/http-port.js +78 -0
  56. package/dist/vendor/@agentims/adapter/dist/interactions/record.js +44 -0
  57. package/dist/vendor/@agentims/adapter/dist/interactions/source.js +113 -0
  58. package/dist/vendor/@agentims/adapter/dist/interactions/types.js +1 -0
  59. package/dist/vendor/@agentims/adapter/dist/receipts/original.js +15 -0
  60. package/dist/vendor/@agentims/adapter/dist/receipts/send.js +7 -1
  61. package/dist/vendor/@agentims/adapter/dist/source/event-source.js +21 -2
  62. package/dist/vendor/@agentims/adapter/dist/source/inbound-binding.js +52 -0
  63. package/dist/vendor/@agentims/adapter/dist/source/inbound-reconcile.js +151 -0
  64. package/dist/vendor/@agentims/adapter/dist/source/inbound-subscription.js +81 -0
  65. package/dist/vendor/@agentims/adapter/dist/source/inbound-types.js +1 -0
  66. package/dist/vendor/@agentims/adapter/package.json +2 -2
  67. package/dist/vendor/@agentims/runtime/dist/cli/commands/catalog.js +2 -1
  68. package/dist/vendor/@agentims/runtime/dist/cli/commands/interactions.js +37 -0
  69. package/dist/vendor/@agentims/runtime/dist/cli/help.js +2 -1
  70. package/dist/vendor/@agentims/runtime/dist/index.js +4 -1
  71. package/dist/vendor/@agentims/runtime/package.json +3 -3
  72. package/dist/vendor/@agentims/sdk/dist/api/client.js +13 -0
  73. package/dist/vendor/@agentims/sdk/dist/api/facade.js +6 -0
  74. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/account-operations.js +117 -0
  75. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/authority.js +92 -0
  76. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/budget.js +48 -0
  77. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/catalog.js +168 -0
  78. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/client.js +146 -0
  79. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/conversation-receipt.js +92 -0
  80. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/device-capabilities.js +64 -0
  81. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/dispatch-fence.js +50 -0
  82. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/errors.js +14 -0
  83. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/host-types.js +1 -0
  84. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/index.js +9 -0
  85. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/invitation-directory.js +80 -0
  86. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/media-streams.js +117 -0
  87. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/original-media.js +25 -0
  88. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/original-receipt.js +158 -0
  89. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/receipt-origins.js +141 -0
  90. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/receipt.js +42 -0
  91. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/resources.js +64 -0
  92. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/results.js +32 -0
  93. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/room-directory.js +104 -0
  94. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/scoped-execution.js +105 -0
  95. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/scoped-intent.js +90 -0
  96. package/dist/vendor/@agentims/sdk/dist/features/agent-operations/types.js +3 -0
  97. package/dist/vendor/@agentims/sdk/dist/features/deliveries/client.js +22 -0
  98. package/dist/vendor/@agentims/sdk/dist/features/deliveries/scoped-replies.js +76 -0
  99. package/dist/vendor/@agentims/sdk/dist/features/deliveries/scoped-status.js +36 -0
  100. package/dist/vendor/@agentims/sdk/dist/features/interactions/client.js +49 -0
  101. package/dist/vendor/@agentims/sdk/dist/features/interactions/countdown.js +56 -0
  102. package/dist/vendor/@agentims/sdk/dist/features/interactions/index.js +6 -0
  103. package/dist/vendor/@agentims/sdk/dist/features/interactions/protocol.js +196 -0
  104. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionField.js +73 -0
  105. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionNativeAppearance.js +31 -0
  106. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionNativeContext.js +40 -0
  107. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionQuery.js +44 -0
  108. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionRequest.js +195 -0
  109. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionResponse.js +91 -0
  110. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionStatus.js +151 -0
  111. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas/InteractionTiming.js +34 -0
  112. package/dist/vendor/@agentims/sdk/dist/features/interactions/schemas.js +20 -0
  113. package/dist/vendor/@agentims/sdk/dist/features/interactions/types.js +3 -0
  114. package/dist/vendor/@agentims/sdk/dist/features/interactions/validation.js +111 -0
  115. package/dist/vendor/@agentims/sdk/dist/features/reliability/legacy-outbox.js +1 -0
  116. package/dist/vendor/@agentims/sdk/dist/features/timeline/client.js +1 -1
  117. package/dist/vendor/@agentims/sdk/dist/index.js +5 -0
  118. package/dist/vendor/@agentims/sdk/dist/internal/native/binding.js +42 -1
  119. package/dist/vendor/@agentims/sdk/dist/internal/native/legacy-outbox.js +102 -0
  120. package/dist/vendor/@agentims/sdk/dist/internal/native/transport.js +2 -2
  121. package/dist/vendor/@agentims/sdk/dist/internal/protocol/operations.json +1 -1
  122. package/dist/vendor/@agentims/sdk/dist/internal/transport/client.js +2 -2
  123. package/dist/vendor/@agentims/sdk/dist/internal/transport/request.js +2 -0
  124. package/dist/vendor/@agentims/sdk/package.json +1 -1
  125. package/package.json +2 -2
  126. package/release.json +130 -54
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)
@@ -85,9 +85,12 @@ export class HostAgentIMAssembly {
85
85
  // The local binding still identifies the original checkpoint and idempotency records.
86
86
  const binding = old?.binding ?? granted;
87
87
  const active = this.channel;
88
- if (active?.executionId === executionId && sameBinding(active.grant, grant)) {
89
- active.grant = grant;
88
+ if (active?.executionId === executionId && sameReceiver(active.grant, grant)) {
90
89
  try {
90
+ if (canonicalBotJson(active.grant.outbound ?? null) !==
91
+ canonicalBotJson(grant.outbound ?? null))
92
+ active.pump.updateOutbound(grant.outbound);
93
+ active.grant = grant;
91
94
  await this.checkDevice(active.account.client, binding, { timeoutMs: 3000 });
92
95
  return;
93
96
  }
@@ -121,7 +124,7 @@ export class HostAgentIMAssembly {
121
124
  }
122
125
  try {
123
126
  const authority = () => {
124
- if (!this.channel || !this.authorized(this.channel))
127
+ if (!this.channel || this.channel !== channel || !this.authorized(channel))
125
128
  throw new Error('AGENTIM_BINDING_UNAVAILABLE');
126
129
  };
127
130
  const pump = this.create({
@@ -129,8 +132,49 @@ export class HostAgentIMAssembly {
129
132
  binding,
130
133
  initialCheckpoint: account.checkpoint,
131
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
+ },
132
175
  }, authority, botId);
133
- this.channel = { executionId, grant, account, pump };
176
+ const channel = { executionId, grant, account, pump };
177
+ this.channel = channel;
134
178
  pump.start();
135
179
  }
136
180
  catch (error) {
@@ -168,7 +212,8 @@ export class HostAgentIMAssembly {
168
212
  await this.disconnect();
169
213
  }
170
214
  }
171
- /** 续期更新原租约,不重置设备、房间或已知输入。 */
172
- function sameBinding(a, b) {
173
- return canonicalBotJson({ ...a, expiresAtMs: b.expiresAtMs }) === canonicalBotJson(b);
215
+ /** 续期和出站委托可独立变化;其余绑定事实继续决定接收器身份。 */
216
+ function sameReceiver(a, b) {
217
+ return (canonicalBotJson({ ...a, expiresAtMs: b.expiresAtMs, outbound: null }) ===
218
+ canonicalBotJson({ ...b, outbound: null }));
174
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 { BotContractError, 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);
14
47
  }
15
- handle(raw, signal) {
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'));
53
+ }
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,20 +64,123 @@ 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));
40
184
  }
41
185
  if (request.operation !== 'schema' && request.operation !== 'call')
42
186
  return Promise.reject(new Error('AGENTIM_OPERATION_INVALID'));
@@ -55,67 +199,109 @@ export class AgentIMCalls {
55
199
  hint: 'Pass the SDK operationId at the top level. The SDK schema describes only input.',
56
200
  });
57
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);
212
+ }
58
213
  if (request.operation === 'schema')
59
214
  return Promise.resolve(directAgentIMSchema(operationId));
60
215
  const operation = directAgentIMOperation(operationId), id = botId(request.requestId);
61
216
  const input = directAgentIMInput(operationId, request.input, id);
62
- const digest = directAgentIMDigest(operationId, input);
63
217
  const body = input.body;
64
218
  const sdkRequestId = typeof body?.request_id === 'string' ? body.request_id : undefined;
65
- // AS 调用 ID 与 SDK request_id 可以不同;未知写仍必须给出真实上游回查定位。
66
- const annotate = (value) => value && typeof value === 'object' && 'state' in value && value.state === 'UNKNOWN'
67
- ? { ...value, operationId, ...(sdkRequestId ? { sdkRequestId } : {}) }
68
- : 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) {
69
290
  const previous = this.active.get(id);
70
291
  if (previous)
71
292
  return previous.digest === digest
72
293
  ? previous.result
73
294
  : Promise.reject(new Error('AGENTIM_CALL_CONFLICT'));
74
- const stop = new AbortController();
75
- const cancelled = AbortSignal.any([stop.signal, ...(signal ? [signal] : [])]);
76
295
  const work = Promise.resolve()
77
- .then(async () => {
78
- if (operation.effect === 'read')
79
- return callDirectAgentIM(this.config, operationId, input, undefined, {
80
- signal: cancelled,
81
- }).catch(directAgentIMFailure);
82
- const saved = this.journal.communication.lookupCall(this.key, id, digest);
83
- if (saved)
84
- return annotate(saved.value);
85
- let value, recorded = false;
86
- try {
87
- value = await callDirectAgentIM(this.config, operationId, input, () => {
88
- const prior = this.journal.communication.reserveCall(this.key, id, digest);
89
- recorded = !prior;
90
- return prior;
91
- }, { signal: cancelled });
92
- }
93
- catch (error) {
94
- // 身份查询期间取消尚未派发;真正intent之后取消仍保存原UNKNOWN,不能重发。
95
- value =
96
- !recorded && cancelled.aborted
97
- ? {
98
- state: 'REJECTED',
99
- disposition: 'NOT_SENT',
100
- code: 'AGENTIM_CALL_CANCELLED',
101
- requestId: id,
102
- operationId,
103
- }
104
- : annotate({ ...directAgentIMFailure(error), requestId: id, operationId });
105
- }
106
- if (recorded)
107
- this.journal.communication.callResult(this.key, id, value);
108
- return value;
109
- })
296
+ .then(run)
110
297
  .finally(() => this.active.delete(id));
111
- this.active.set(id, { digest, result: work, stop });
298
+ this.active.set(id, { digest, result: work });
112
299
  return work;
113
300
  }
114
301
  /** 只排空本连接操作,关闭不注销账号或停止官方 daemon。 */
115
302
  async close() {
116
303
  this.closed = true;
117
- for (const call of this.active.values())
118
- call.stop.abort();
304
+ this.scopeLifetime.abort(new Error('AGENTIM_BINDING_UNAVAILABLE'));
119
305
  await Promise.allSettled([...this.active.values()].map((value) => value.result));
120
306
  }
121
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
+ }