@ixo/oracle-runtime-workers 0.31.0 → 0.32.0

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.
@@ -1,8 +1,6 @@
1
1
  import {
2
2
  CHAIN_TX_MAX_MESSAGES,
3
- CHAIN_TX_MAX_TOKEN_LINES,
4
3
  CHAIN_TX_MESSAGE_TYPES,
5
- DENOM,
6
4
  operationJsonSchema,
7
5
  parseOperation,
8
6
  type ActionOutcomeV1,
@@ -10,6 +8,14 @@ import {
10
8
  type ActionReferenceV1,
11
9
  type ChainTxMessageType,
12
10
  } from '@ixo/action-protocol';
11
+ import {
12
+ AIMessage,
13
+ ToolMessage,
14
+ type BaseMessage,
15
+ } from '@langchain/core/messages';
16
+ import { tool } from '@langchain/core/tools';
17
+ import { convertToOpenAITool } from '@langchain/core/utils/function_calling';
18
+ import { createMiddleware, type AgentMiddleware } from 'langchain';
13
19
  import { z } from 'zod';
14
20
  import { quoteHubText } from '../../hub-actions/hub-text';
15
21
  import { OraclePlugin } from '../../plugin-api/oracle-plugin';
@@ -20,6 +26,19 @@ import type {
20
26
  RuntimeContext,
21
27
  } from '../../plugin-api/types';
22
28
  import { ixoAddressOf } from '../../core/user-identity';
29
+ import { toolNotRunMessage } from '../../core/tool-not-run';
30
+ import {
31
+ CHAIN_TX_CATALOG,
32
+ CHAIN_TX_GENERAL_RULES,
33
+ chainTxMessageInput,
34
+ hasUnsafeText,
35
+ } from './chain-tx-catalog';
36
+
37
+ export {
38
+ CHAIN_TX_CATALOG,
39
+ CHAIN_TX_GENERAL_RULES,
40
+ hasUnsafeText,
41
+ } from './chain-tx-catalog';
23
42
 
24
43
  const configSchema = z.object({
25
44
  HUB_ACTIONS_ENABLED: z.enum(['true', 'false']).default('false'),
@@ -65,192 +84,7 @@ const statusSchema = z.strictObject({
65
84
  });
66
85
  const discoverSchema = z.strictObject({});
67
86
 
68
- /**
69
- * The messages of one chain transaction (`ixo.chain.tx.v1`), as the model
70
- * writes them. The shapes are the protocol's minus the owner's identity
71
- * (a claim's `agentDid`, an evaluation's `agentAddress`), which the runtime
72
- * fills, as it fills the chain id, network and signer; a bank step names a
73
- * display amount, which the owner object converts to base units from the
74
- * owner's token list. The protocol parses the whole operation again before
75
- * it reaches the Hub. The rules match Auth Hub's (ids, address length, DID
76
- * escapes, memo characters), so a message the Hub would refuse is refused
77
- * here, before any Hub call.
78
- */
79
- /** A 20-byte bech32 account address: `ixo1` and 38 characters (a 32-byte contract address is longer). */
80
- const IXO_ADDRESS = /^ixo1[023456789acdefghjklmnpqrstuvwxyz]{38}$/;
81
- const BASE_UNITS = /^[1-9][0-9]{0,77}$/;
82
- /** A DID; `%` only as a `%xx` escape. */
83
- const ANY_DID = /^did:[a-z0-9]+:(?:[A-Za-z0-9._:-]|%[0-9A-Fa-f]{2})+$/;
84
- /** Claim, collection, token and proof ids: no spaces, quotes or markup. */
85
- const ID_CHARS = /^[A-Za-z0-9:._/-]+$/;
86
- const ID_RULE = 'Only letters, digits and : . _ / - (copied exactly).';
87
- /**
88
- * Characters that would let text render as something else: C0 and C1
89
- * controls, zero-width and direction marks (U+200B–U+200F), line and
90
- * paragraph separators (U+2028–U+2029), bidi embeddings, overrides and
91
- * isolates (U+202A–U+202E, U+2066–U+2069), the Arabic letter mark (U+061C)
92
- * and the byte order mark (U+FEFF). Auth Hub refuses the same set.
93
- */
94
- export function hasUnsafeText(value: string): boolean {
95
- for (const char of value) {
96
- const code = char.codePointAt(0) ?? 0;
97
- if (
98
- code <= 0x1f ||
99
- (code >= 0x7f && code <= 0x9f) ||
100
- code === 0x061c ||
101
- (code >= 0x200b && code <= 0x200f) ||
102
- (code >= 0x2028 && code <= 0x202e) ||
103
- (code >= 0x2066 && code <= 0x2069) ||
104
- code === 0xfeff
105
- )
106
- return true;
107
- }
108
- return false;
109
- }
110
87
  const MEMO_BYTES = 256;
111
- const address = (what: string) =>
112
- z
113
- .string()
114
- .regex(
115
- IXO_ADDRESS,
116
- 'A 20-byte ixo1… account address (42 characters); contract addresses are refused.',
117
- )
118
- .describe(`${what} (an ixo1… account address).`);
119
- const id = (max: number) => z.string().min(1).max(max).regex(ID_CHARS, ID_RULE);
120
- const baseUnits = (what: string) =>
121
- z
122
- .string()
123
- .regex(BASE_UNITS, 'A whole number of base units above zero.')
124
- .describe(what);
125
- const claimId = id(256).describe('The claim id, exactly as stored.');
126
- const collectionId = z
127
- .string()
128
- .regex(/^(0|[1-9][0-9]{0,19})$/, 'Digits only, no leading zeros.')
129
- .describe('The claim collection id (digits).');
130
-
131
- /** A display amount: a plain decimal in the token's units, as the user said it. */
132
- const DISPLAY_AMOUNT = /^(0|[1-9][0-9]*)(\.[0-9]+)?$/;
133
-
134
- /**
135
- * One chain-transaction message type: the one-line `summary` the request
136
- * tool's description lists, the full `rules` describe_chain_messages
137
- * returns (with the fields of `schema`), and the strict `schema` the
138
- * request handler checks each message against. Adding a message type is
139
- * one entry here (once `@ixo/action-protocol` and Auth Hub support it).
140
- */
141
- interface ChainTxCatalogEntry {
142
- summary: string;
143
- rules: string;
144
- schema: z.ZodObject;
145
- }
146
-
147
- export const CHAIN_TX_CATALOG = {
148
- 'cosmos.bank.send': {
149
- summary:
150
- "send coins (IXO or another token the owner holds) from the owner's wallet.",
151
- rules: [
152
- "Sends coins from the owner's wallet to `toAddress`, alone (a single coin send) or as a step of a batch.",
153
- '`amount` is the amount as the user said it, in the token’s display units ("1.5" for 1.5 IXO): a plain decimal, never base units. The runtime looks the token up in the owner’s token list (hub_action_options `transfer.tokens`), converts the amount with the listed `decimals`, and refuses a token not in the list, more digits after the point than the token has, zero, and more than the listed balance (the bank steps of one token together).',
154
- '`denom` is optional and defaults to uixo (IXO, 6 decimals). For another token copy its `denom` exactly from `transfer.tokens` (never guess an `ibc/…` hash); name the full denom to the owner for anything but IXO, and say when the token is unverified (it lists 0 decimals: its amount is a whole number of base units).',
155
- ].join(' '),
156
- schema: z.strictObject({
157
- type: z.literal('cosmos.bank.send'),
158
- toAddress: address('The recipient'),
159
- amount: z
160
- .string()
161
- .max(80)
162
- .regex(
163
- DISPLAY_AMOUNT,
164
- 'A plain decimal amount in the token’s display units, such as 1.5 (never base units).',
165
- )
166
- .describe(
167
- 'The amount as the user said it, in the token’s display units (1.5 = 1.5 IXO).',
168
- ),
169
- denom: z
170
- .string()
171
- .regex(DENOM, 'A denom exactly as hub_action_options lists it.')
172
- .optional()
173
- .describe(
174
- 'The token’s denom, copied exactly from hub_action_options `transfer.tokens`; leave out for uixo (IXO).',
175
- ),
176
- }),
177
- },
178
- 'ixo.claims.submit': {
179
- summary:
180
- 'file a claim the owner has already created with a claim collection.',
181
- rules:
182
- 'Files a claim the owner has already created with a claim collection. `claimId` is the stored claim’s id, `collectionId` the collection, `adminAddress` the collection admin’s address. The runtime adds the owner’s DID as the filer. The collection admin must have authorized the owner to submit claims. Collections with member budgets cannot be filed into here (no member address is sent). Set `useIntent` only when the collection works with intents.',
183
- schema: z.strictObject({
184
- type: z.literal('ixo.claims.submit'),
185
- collectionId,
186
- claimId,
187
- adminAddress: address("The collection admin's address"),
188
- useIntent: z
189
- .boolean()
190
- .optional()
191
- .describe('true only when the collection pays claims through intents.'),
192
- }),
193
- },
194
- 'ixo.claims.evaluate': {
195
- summary:
196
- 'record the owner’s decision, as evaluator, on someone else’s claim (approve, reject, dispute, invalidate).',
197
- rules:
198
- 'Records the owner’s decision, as evaluator, on someone else’s claim (`claimId` in `collectionId`). `status` 1 approve, 2 reject, 3 dispute (the chain may refuse it as deprecated), 4 invalidate. It is recorded as the owner’s (the runtime adds their DID and address, never the claimant’s); `oracle` is the evaluator DID recorded on the evaluation (normally the owner’s DID, or the oracle entity DID the collection admin authorized); `adminAddress` is the collection admin’s address; `reason` (a number) and `verificationProof` are optional. The collection admin must have authorized the owner as an evaluator. An approval can pay the claimant.',
199
- schema: z.strictObject({
200
- type: z.literal('ixo.claims.evaluate'),
201
- claimId,
202
- collectionId,
203
- oracle: z
204
- .string()
205
- .max(200)
206
- .regex(ANY_DID, 'A DID (did:<method>:…; % only as %xx).')
207
- .describe('The evaluator DID recorded on the evaluation (a did:…).'),
208
- adminAddress: address("The collection admin's address"),
209
- status: z
210
- .literal([1, 2, 3, 4])
211
- .describe(
212
- '1 approve, 2 reject, 3 dispute (the chain may refuse it as deprecated), 4 invalidate.',
213
- ),
214
- reason: z
215
- .number()
216
- .int()
217
- .min(0)
218
- .max(4_294_967_295)
219
- .optional()
220
- .describe("The evaluator's reason code, when there is one."),
221
- verificationProof: id(300)
222
- .optional()
223
- .describe(
224
- 'The evaluation proof (a credential CID), when there is one.',
225
- ),
226
- }),
227
- },
228
- 'ixo.token.transfer': {
229
- summary:
230
- "move IXO impact tokens (1155-style token ids, whole amounts) from the owner's wallet.",
231
- rules: `Moves IXO impact tokens (1155-style: each line a token \`id\` of 32 hex characters and a whole \`amount\`, 1 to ${CHAIN_TX_MAX_TOKEN_LINES} lines) from the owner’s wallet to \`recipient\`. Impact tokens have no decimals: an amount is a whole number of tokens. All tokens in one message must come from one token contract. These are not the IXO coin: coins go through \`cosmos.bank.send\`.`,
232
- schema: z.strictObject({
233
- type: z.literal('ixo.token.transfer'),
234
- recipient: address('The recipient'),
235
- tokens: z
236
- .array(
237
- z.strictObject({
238
- id: id(128).describe(
239
- 'The impact token id (32 hex characters), exactly as listed.',
240
- ),
241
- amount: baseUnits('A whole number of tokens above zero.'),
242
- }),
243
- )
244
- .min(1)
245
- .max(CHAIN_TX_MAX_TOKEN_LINES),
246
- }),
247
- },
248
- } as const satisfies Record<ChainTxMessageType, ChainTxCatalogEntry>;
249
-
250
- /** What every message type shares, returned once by describe_chain_messages. */
251
- export const CHAIN_TX_GENERAL_RULES =
252
- 'Addresses are 20-byte `ixo1…` account addresses (contract addresses are refused). Ids (`claimId`, `collectionId`, token `id`, `verificationProof`) use only letters, digits and `: . _ / -`; copy them exactly and never invent them. Give only the fields listed for a type: the runtime adds the chain, the network, the signer and the owner’s own DID and address where a message needs them, and Auth Hub sets the fee. Up to 8 messages per transaction, run in order; all succeed or none do.';
253
-
254
88
  const memoSchema = z
255
89
  .string()
256
90
  .max(MEMO_BYTES)
@@ -279,6 +113,8 @@ export function fieldsOnly(schema: z.core.$ZodType): z.ZodType {
279
113
  );
280
114
  if (schema instanceof z.ZodOptional)
281
115
  return fieldsOnly(schema.unwrap()).optional();
116
+ if (schema instanceof z.ZodNullable)
117
+ return fieldsOnly(schema.unwrap()).nullable();
282
118
  if (schema instanceof z.ZodArray) return z.array(fieldsOnly(schema.element));
283
119
  if (schema instanceof z.ZodString) return z.string();
284
120
  if (schema instanceof z.ZodNumber) return z.number();
@@ -307,17 +143,34 @@ function messageFieldsOnly(schema: z.ZodObject) {
307
143
  }
308
144
 
309
145
  /**
310
- * The schema the model is given: per type, its fields (messageFieldsOnly),
311
- * so a type adds its short field list and the rules are fetched with
312
- * describe_chain_messages when needed. Each message is then checked by the
313
- * handler against its full catalogue schema.
146
+ * The schema the model is given: per type its fields (messageFieldsOnly)
147
+ * when the type was described in this session (`described`; absent: every
148
+ * type), and one open branch naming every other type (`type` one of them,
149
+ * any other field allowed). A type the model has not read about costs its
150
+ * name only; the request handler refuses it until it is described, and
151
+ * the next model call is given its fields (`chainTxFieldsMiddleware`).
152
+ * Each message is checked by the handler against its full catalogue
153
+ * schema.
314
154
  */
315
155
  export function chainTransactionSchemaFor(
316
156
  catalog: Readonly<Record<string, { schema: z.ZodObject }>>,
157
+ described?: ReadonlySet<string>,
317
158
  ) {
318
- const [first, ...rest] = Object.values(catalog).map((entry) =>
319
- messageFieldsOnly(entry.schema),
320
- );
159
+ const entries = Object.entries(catalog);
160
+ const withFields = entries
161
+ .filter(([type]) => !described || described.has(type))
162
+ .map(([, entry]) => messageFieldsOnly(entry.schema));
163
+ const [firstUnread, ...unread] = entries
164
+ .filter(([type]) => described && !described.has(type))
165
+ .map(([type]) => type);
166
+ const branches =
167
+ firstUnread === undefined
168
+ ? withFields
169
+ : [
170
+ ...withFields,
171
+ z.looseObject({ type: z.literal([firstUnread, ...unread]) }),
172
+ ];
173
+ const [first, ...rest] = branches;
321
174
  if (!first) throw new Error('The chain transaction catalogue is empty');
322
175
  return z.strictObject({
323
176
  messages: z
@@ -327,7 +180,6 @@ export function chainTransactionSchemaFor(
327
180
  memo: memoSchema,
328
181
  });
329
182
  }
330
- const chainTransactionSchema = chainTransactionSchemaFor(CHAIN_TX_CATALOG);
331
183
 
332
184
  /**
333
185
  * The request tool's description: what it does, the discovery step, one
@@ -342,9 +194,285 @@ export function chainTransactionDescription(
342
194
  ...Object.entries(catalog).map(
343
195
  ([type, entry]) => `- \`${type}\`: ${entry.summary}`,
344
196
  ),
345
- 'Up to 8 messages run in order as one transaction: all succeed or none do. Never invent ids or addresses (ask the owner or use other tools); coin amounts are display units ("1.5"), never base units. When the result is unavailable, tell the owner its reason in plain words; when it says retrying or changing the fields will not help, do not retry.',
197
+ 'Up to 8 messages run in order as one transaction: all succeed or none do. Never invent ids or addresses (ask the owner or use other tools); coin and stake amounts are display units ("1.5"), never base units. Tell the owner what will happen in plain everyday words, never message type names or chain terms. When the result is unavailable, tell the owner its reason in plain words; when it says retrying or changing the fields will not help, do not retry.',
346
198
  ].join('\n');
347
199
  }
200
+
201
+ /** The catalogue entries of `types`, in catalogue order. */
202
+ function catalogOf(types: readonly ChainTxMessageType[]) {
203
+ return Object.fromEntries(
204
+ CHAIN_TX_MESSAGE_TYPES.filter((type) => types.includes(type)).map(
205
+ (type) => [type, CHAIN_TX_CATALOG[type]],
206
+ ),
207
+ );
208
+ }
209
+
210
+ /**
211
+ * request_chain_transaction for the message types this account may use
212
+ * (`availableChainTxTypes`): the model is given their summaries, and the
213
+ * fields of those `described` in this session (null: of every one), so it
214
+ * neither sees nor pays for a type Auth Hub would refuse or one it has not
215
+ * read about, and its arguments are checked against the same schema (a
216
+ * message of another type is refused before any Hub call). Null when the
217
+ * account may use none (describe_chain_messages then answers
218
+ * `availableTypes: []`). Built once per (types, described) pair.
219
+ */
220
+ export function chainTransactionTool(
221
+ types: readonly ChainTxMessageType[],
222
+ described: readonly ChainTxMessageType[] | null = null,
223
+ ): PluginTool | null {
224
+ const catalog = catalogOf(types);
225
+ if (!Object.keys(catalog).length) return null;
226
+ const fields = described
227
+ ? new Set(
228
+ Object.keys(catalog).filter((type) =>
229
+ described.some((d) => d === type),
230
+ ),
231
+ )
232
+ : undefined;
233
+ const key = `${Object.keys(catalog).join(',')}|${fields ? [...fields].join(',') : '*'}`;
234
+ const cached = chainTransactionTools.get(key);
235
+ if (cached) {
236
+ // Most recently used last, so the bound below drops the oldest.
237
+ chainTransactionTools.delete(key);
238
+ chainTransactionTools.set(key, cached);
239
+ return cached;
240
+ }
241
+ const schema = chainTransactionSchemaFor(catalog, fields);
242
+ const tool: PluginTool = {
243
+ name: 'request_chain_transaction',
244
+ description: chainTransactionDescription(catalog),
245
+ schema,
246
+ effect: 'write',
247
+ handler: (input, ctx) => requestChainTransaction(schema, input, ctx),
248
+ };
249
+ // Type lists come from Auth Hub capabilities (one or two per deployment)
250
+ // and described sets from sessions; the bound keeps the map small, the
251
+ // least recently used pair is built again when needed.
252
+ if (chainTransactionTools.size >= CHAIN_TRANSACTION_TOOL_CACHE)
253
+ chainTransactionTools.delete(chainTransactionTools.keys().next().value!);
254
+ chainTransactionTools.set(key, tool);
255
+ return tool;
256
+ }
257
+ const CHAIN_TRANSACTION_TOOL_CACHE = 32;
258
+
259
+ /**
260
+ * The message types described in a conversation (`describe_chain_messages`),
261
+ * per session id in the owner's own key-value rows, each with the run that
262
+ * first described it: durable across restarts of the owner object, kept
263
+ * while used (`DESCRIBED_IDLE_TTL_MS`), and at most `DESCRIBED_MAX_SESSIONS`
264
+ * sessions per owner. A new session starts with none.
265
+ */
266
+ const DESCRIBED_NAMESPACE = 'hub-actions/chain-tx-described';
267
+ const DESCRIBED_IDLE_TTL_MS = 7 * 24 * 60 * 60_000;
268
+ const DESCRIBED_MAX_SESSIONS = 200;
269
+
270
+ /** The stored `{type: runId}` record of a session (anything else: none). */
271
+ function describedRecord(
272
+ value: unknown,
273
+ ): Partial<Record<ChainTxMessageType, string>> {
274
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
275
+ const record: Partial<Record<ChainTxMessageType, string>> = {};
276
+ for (const type of CHAIN_TX_MESSAGE_TYPES) {
277
+ const run: unknown = Reflect.get(value, type);
278
+ if (typeof run === 'string') record[type] = run;
279
+ }
280
+ return record;
281
+ }
282
+
283
+ /**
284
+ * The types whose rules a `describe_chain_messages` call in `messages` read:
285
+ * its arguments (on the AI message that made the call), counted only when
286
+ * its result is there too and is not an error.
287
+ */
288
+ function describedInHistory(
289
+ messages: readonly BaseMessage[],
290
+ ): Set<ChainTxMessageType> {
291
+ const calls = new Map<string, unknown>();
292
+ for (const message of messages)
293
+ if (AIMessage.isInstance(message))
294
+ for (const call of message.tool_calls ?? [])
295
+ if (call.name === 'describe_chain_messages' && call.id)
296
+ calls.set(call.id, call.args);
297
+ const described = new Set<ChainTxMessageType>();
298
+ for (const message of messages) {
299
+ if (
300
+ !ToolMessage.isInstance(message) ||
301
+ message.name !== 'describe_chain_messages' ||
302
+ message.status === 'error'
303
+ )
304
+ continue;
305
+ const args = describeChainMessagesSchema.safeParse(
306
+ calls.get(message.tool_call_id),
307
+ );
308
+ if (args.success) for (const type of args.data.types) described.add(type);
309
+ }
310
+ return described;
311
+ }
312
+
313
+ /** This turn in the session: `${sessionId}|${runId}`. */
314
+ const runKeyOf = (ctx: RuntimeContext) =>
315
+ `${ctx.session.id}|${ctx.session.runId ?? ''}`;
316
+
317
+ /**
318
+ * Turns whose described types could not be stored: they fall back to every
319
+ * type's fields and no refusal (a store failure must not make chain cards
320
+ * unusable). Bounded; the oldest turn is dropped first.
321
+ */
322
+ const UNSTORED_TURNS_MAX = 256;
323
+ const unstoredTurns = new Set<string>();
324
+
325
+ /**
326
+ * The types this call may use (and whose fields the model is given), by
327
+ * one rule: described in the history this call sees (`messages`), or
328
+ * stored by an earlier run of the session. A type the current run stored
329
+ * counts only once its `describe_chain_messages` result is in that history,
330
+ * so a describe made in the same model response as the request (a parallel
331
+ * call) never lets the request through, whichever finishes first. Null when
332
+ * the session cannot remember (no store or session, or the store failed):
333
+ * every type then carries its fields and none is refused.
334
+ */
335
+ async function describedChainTxTypes(
336
+ ctx: RuntimeContext,
337
+ messages: readonly BaseMessage[],
338
+ ): Promise<ChainTxMessageType[] | null> {
339
+ if (!ctx.kv || !ctx.session.id || unstoredTurns.has(runKeyOf(ctx)))
340
+ return null;
341
+ let stored: Partial<Record<ChainTxMessageType, string>>;
342
+ try {
343
+ stored = describedRecord(
344
+ await ctx.kv.get(DESCRIBED_NAMESPACE, ctx.session.id),
345
+ );
346
+ } catch (error) {
347
+ ctx.logger.warn(
348
+ `[hub-actions] described chain message types unreadable; every type keeps its fields: ${error instanceof Error ? error.message : String(error)}`,
349
+ );
350
+ return null;
351
+ }
352
+ const inHistory = describedInHistory(messages);
353
+ const runId = ctx.session.runId ?? '';
354
+ return CHAIN_TX_MESSAGE_TYPES.filter(
355
+ (type) =>
356
+ inHistory.has(type) ||
357
+ (stored[type] !== undefined && stored[type] !== runId),
358
+ );
359
+ }
360
+
361
+ /** Records the described types; a type keeps the run that first described it. */
362
+ async function rememberDescribed(
363
+ ctx: RuntimeContext,
364
+ types: readonly ChainTxMessageType[],
365
+ ): Promise<void> {
366
+ if (!ctx.kv || !ctx.session.id) return;
367
+ const runId = ctx.session.runId ?? '';
368
+ try {
369
+ await ctx.kv.update(
370
+ DESCRIBED_NAMESPACE,
371
+ ctx.session.id,
372
+ (current) => ({
373
+ ...Object.fromEntries(types.map((type) => [type, runId])),
374
+ ...describedRecord(current),
375
+ }),
376
+ { idleTtlMs: DESCRIBED_IDLE_TTL_MS, maxEntries: DESCRIBED_MAX_SESSIONS },
377
+ );
378
+ } catch (error) {
379
+ ctx.logger.warn(
380
+ `[hub-actions] described chain message types not stored; this turn gives every type's fields: ${error instanceof Error ? error.message : String(error)}`,
381
+ );
382
+ if (unstoredTurns.size >= UNSTORED_TURNS_MAX)
383
+ unstoredTurns.delete(unstoredTurns.values().next().value!);
384
+ unstoredTurns.add(runKeyOf(ctx));
385
+ }
386
+ }
387
+
388
+ /**
389
+ * The account's chain types for a turn, read once (by the request tool and
390
+ * then reused by `chainTxFieldsMiddleware` for every model call).
391
+ */
392
+ const turnChainTxTypes = new WeakMap<
393
+ RuntimeContext,
394
+ Promise<readonly ChainTxMessageType[]>
395
+ >();
396
+ function chainTxTypesForTurn(
397
+ ctx: RuntimeContext,
398
+ ): Promise<readonly ChainTxMessageType[]> {
399
+ let types = turnChainTxTypes.get(ctx);
400
+ if (!types) {
401
+ types = availableChainTxTypes(ctx);
402
+ turnChainTxTypes.set(ctx, types);
403
+ }
404
+ return types;
405
+ }
406
+
407
+ /** The function definition of a request tool, per description, built once. */
408
+ const toolDefinitions = new WeakMap<
409
+ PluginTool,
410
+ Map<string, Record<string, unknown>>
411
+ >();
412
+ function definitionOf(
413
+ pluginTool: PluginTool,
414
+ description: string,
415
+ ): Record<string, unknown> {
416
+ let byDescription = toolDefinitions.get(pluginTool);
417
+ if (!byDescription) {
418
+ byDescription = new Map();
419
+ toolDefinitions.set(pluginTool, byDescription);
420
+ }
421
+ let definition = byDescription.get(description);
422
+ if (!definition) {
423
+ const { type, function: fn } = convertToOpenAITool(
424
+ tool(async () => '', {
425
+ name: pluginTool.name,
426
+ description,
427
+ schema: pluginTool.schema,
428
+ }),
429
+ );
430
+ // A plain object (a server-tool definition to LangChain), not a tool
431
+ // instance: LangChain refuses a new instance of a registered tool.
432
+ definition = { type, function: fn };
433
+ byDescription.set(description, definition);
434
+ }
435
+ return definition;
436
+ }
437
+
438
+ /**
439
+ * The per-turn tool is built before the turn's first model call, so a type
440
+ * described during the turn would reach the next model call without its
441
+ * fields, and a provider drops fields its schema does not declare (the
442
+ * 0.29.0 failure). Before each model call this gives the model the request
443
+ * tool for what is described by then (`describedChainTxTypes` over the
444
+ * call's messages), as its function definition with the registered tool's
445
+ * name and description; the registered tool, whose schema accepts the
446
+ * fields of every type, still runs the call. A tool the capability gate
447
+ * hid is not in the request, so nothing is added; a failure to read the
448
+ * store leaves the request as it is.
449
+ */
450
+ function chainTxFieldsMiddleware(ctx: RuntimeContext) {
451
+ return createMiddleware({
452
+ name: 'HubActionsChainTxFieldsMiddleware',
453
+ wrapModelCall: async (request, handler) => {
454
+ const index = request.tools.findIndex(
455
+ (entry) => entry.name === 'request_chain_transaction',
456
+ );
457
+ const registered = request.tools[index];
458
+ if (!registered || typeof registered.description !== 'string')
459
+ return handler(request);
460
+ const described = await describedChainTxTypes(ctx, request.messages);
461
+ if (!described) return handler(request);
462
+ const current = chainTransactionTool(
463
+ await chainTxTypesForTurn(ctx),
464
+ described,
465
+ );
466
+ if (!current) return handler(request);
467
+ const tools = [...request.tools];
468
+ tools[index] = definitionOf(current, registered.description);
469
+ return handler({ ...request, tools });
470
+ },
471
+ });
472
+ }
473
+ const chainTransactionTools = new Map<string, PluginTool>();
474
+
475
+ /** The request tool as the whole catalogue gives it (no account capabilities). */
348
476
  export const CHAIN_TRANSACTION_TOOL_DESCRIPTION =
349
477
  chainTransactionDescription(CHAIN_TX_CATALOG);
350
478
 
@@ -360,7 +488,7 @@ const describeChainMessagesSchema = z.strictObject({
360
488
  });
361
489
 
362
490
  export const DESCRIBE_CHAIN_MESSAGES_TOOL_DESCRIPTION =
363
- 'Read the full rules of chain-transaction message types before using them in request_chain_transaction: every field with its meaning, format and limits, what the runtime fills, and chain caveats. Ask only for the types you need. Also returns `availableTypes`: the types this account may use.';
491
+ 'Read the full rules of chain-transaction message types before using them in request_chain_transaction: every field with its meaning, format and limits, what the runtime fills, and chain caveats. Ask only for the types you need: request_chain_transaction takes only types described in this conversation, and gives their fields from the next call on. Also returns `availableTypes`: the types this account may use.';
364
492
 
365
493
  export type HubActionRequestResult =
366
494
  | {
@@ -510,11 +638,33 @@ async function requestHubAction(
510
638
  }
511
639
 
512
640
  async function requestChainTransaction(
641
+ schema: ReturnType<typeof chainTransactionSchemaFor>,
513
642
  input: unknown,
514
643
  ctx: RuntimeContext,
515
- ): Promise<HubActionRequestResult> {
516
- const parsed = chainTransactionSchema.safeParse(input);
644
+ ): Promise<HubActionRequestResult | ToolMessage> {
645
+ const parsed = schema.safeParse(input);
517
646
  if (!parsed.success) return chainTxShapeRefusal(issuesOf(parsed.error));
647
+ const described = await describedChainTxTypes(ctx, ctx.history.messages);
648
+ if (described) {
649
+ const unread = [
650
+ ...new Set(
651
+ parsed.data.messages
652
+ .map(chainTxTypeOf)
653
+ .filter(
654
+ (type): type is ChainTxMessageType =>
655
+ type !== null && !described.includes(type),
656
+ ),
657
+ ),
658
+ ];
659
+ if (unread.length)
660
+ // Not run, and not a failure: the repetition guard lets the same
661
+ // call through once the rules are read.
662
+ return toolNotRunMessage({
663
+ toolCallId: ctx.toolCallId ?? '',
664
+ name: 'request_chain_transaction',
665
+ content: `For you, not the person: nothing was sent and nothing is wrong. Before a card with ${unread.map((type) => `\`${type}\``).join(', ')}, read the rules: call describe_chain_messages with types ${JSON.stringify(unread)}, then call request_chain_transaction again with exactly the fields it lists. Do not mention this step to the person.`,
666
+ });
667
+ }
518
668
  const checked = strictChainTxMessages(parsed.data.messages);
519
669
  if ('issues' in checked) return chainTxShapeRefusal(checked.issues);
520
670
  if (ctx.config.HUB_ACTIONS_ENABLED !== 'true' || !ctx.hubActions)
@@ -576,7 +726,7 @@ function strictChainTxMessages(
576
726
  return;
577
727
  }
578
728
  const result = CHAIN_TX_CATALOG[type].schema.safeParse(message);
579
- if (result.success) checked.push(result.data);
729
+ if (result.success) checked.push(chainTxMessageInput(result.data));
580
730
  else issues.push(...issuesOf(result.error, ['messages', index]));
581
731
  });
582
732
  return issues.length ? { issues } : { messages: checked };
@@ -634,9 +784,12 @@ function issuesOf(
634
784
 
635
785
  /**
636
786
  * The catalogue types this account may use: the Hub capabilities'
637
- * `chainTx.messageTypes` (none when chain transactions are off for the
638
- * account), or the whole catalogue when the capabilities cannot be read
639
- * (not a channel turn, or the Hub did not answer).
787
+ * `chainTx.messageTypes`. None when chain transactions cannot be used
788
+ * here: not a channel turn, Hub actions off, chain transactions off for the
789
+ * account, a Hub at protocol level 5 (the 0.6.0 types only, as it lists
790
+ * them), or capabilities that cannot be read (the owner object answers its
791
+ * last good capabilities while a read fails, and does not retry a failed
792
+ * read for 30 s, so this never holds a turn for long).
640
793
  */
641
794
  async function availableChainTxTypes(
642
795
  ctx: RuntimeContext,
@@ -647,15 +800,15 @@ async function availableChainTxTypes(
647
800
  !ctx.session.channel ||
648
801
  !ctx.hubActions
649
802
  )
650
- return CHAIN_TX_MESSAGE_TYPES;
803
+ return [];
651
804
  let chainTx;
652
805
  try {
653
- chainTx = (await ctx.hubActions.capabilities()).chainTx;
806
+ chainTx = (await ctx.hubActions.capabilities({ turn: true })).chainTx;
654
807
  } catch (error) {
655
808
  ctx.logger.warn(
656
- `[hub-actions] capabilities unavailable for describe_chain_messages: ${error instanceof Error ? error.message : String(error)}`,
809
+ `[hub-actions] capabilities unavailable, no chain transaction types this turn: ${error instanceof Error ? error.message : String(error)}`,
657
810
  );
658
- return CHAIN_TX_MESSAGE_TYPES;
811
+ return [];
659
812
  }
660
813
  return CHAIN_TX_MESSAGE_TYPES.filter((type) =>
661
814
  chainTx?.messageTypes.includes(type),
@@ -686,6 +839,7 @@ async function describeChainMessages(
686
839
  status: 'unavailable',
687
840
  reason: `Name 1 to ${CHAIN_TX_MAX_MESSAGES} different message types, each one of: ${CHAIN_TX_MESSAGE_TYPES.join(', ')}.`,
688
841
  };
842
+ await rememberDescribed(ctx, parsed.data.types);
689
843
  return {
690
844
  status: 'known',
691
845
  general: CHAIN_TX_GENERAL_RULES,
@@ -750,6 +904,16 @@ export function modelOutcome(
750
904
  return { ...outcome, receipt: modelReceipt(outcome.receipt) };
751
905
  }
752
906
 
907
+ /**
908
+ * What a `cancelled` outcome means. Auth Hub withdraws a card when the
909
+ * person cancels it, and also on its own: a chain transaction whose details
910
+ * changed on chain after the review (`409 review_changed`, reason
911
+ * `chain_changed`, shown on the review page only). The oracle gets
912
+ * `cancelled` either way, so the model must not say who withdrew it.
913
+ */
914
+ export const CANCELLED_MEANING =
915
+ 'Withdrawn before anything was sent: nothing happened on chain. The person may have cancelled it, or Auth Hub withdrew it because something it depended on changed after the review; do not say the person cancelled it. If they still want it, offer to prepare a fresh one.';
916
+
753
917
  async function hubActionStatus(
754
918
  input: unknown,
755
919
  ctx: RuntimeContext,
@@ -777,6 +941,9 @@ async function hubActionStatus(
777
941
  operationStatus: read.operationStatus,
778
942
  outcome: modelOutcome(read.outcome),
779
943
  ...(read.summary ? { summary: read.summary } : {}),
944
+ ...(read.outcome?.status === 'cancelled'
945
+ ? { meaning: CANCELLED_MEANING }
946
+ : {}),
780
947
  };
781
948
  } catch (error) {
782
949
  // An Auth Hub that must be updated first: plain words, not a tool error.
@@ -843,6 +1010,8 @@ const manifest: PluginManifest = {
843
1010
  whenToUse: [
844
1011
  'The user requests a registered form submission or a coin send.',
845
1012
  'The user asks to file or evaluate a claim, or to send coins or impact tokens on chain.',
1013
+ 'The user asks to stake, unstake or move IXO, claim staking rewards, vote on a network proposal or retire impact tokens.',
1014
+ 'The user asks to reserve or dispute a claim, create or change a claim collection, give or remove a permission, create or update an entity, or change the links of an identity.',
846
1015
  'The user asks to review an exact private resource or to sign a statement.',
847
1016
  'The user asks to connect Gmail or Calendar, send a reviewed email or add an event.',
848
1017
  'The user asks for document access or to save a private note.',
@@ -871,6 +1040,23 @@ export class HubActionsPlugin extends OraclePlugin {
871
1040
  env.AUTH_HUB_CHANNEL_SERVICE_KEY.length > 0
872
1041
  );
873
1042
  }
1043
+ /**
1044
+ * request_chain_transaction is built per turn: its schema names only the
1045
+ * message types this account may use (Auth Hub capabilities, cached by
1046
+ * the owner object), so 33 types do not reach a model that may use 4.
1047
+ */
1048
+ override async getRequestTools(ctx: RuntimeContext): Promise<PluginTool[]> {
1049
+ const [available, described] = await Promise.all([
1050
+ chainTxTypesForTurn(ctx),
1051
+ describedChainTxTypes(ctx, ctx.history.messages),
1052
+ ]);
1053
+ const tool = chainTransactionTool(available, described);
1054
+ return tool ? [tool] : [];
1055
+ }
1056
+ /** Gives each model call the request tool with the fields described so far in the turn. */
1057
+ override getRequestMiddlewares(ctx: RuntimeContext): AgentMiddleware[] {
1058
+ return [chainTxFieldsMiddleware(ctx)];
1059
+ }
874
1060
  override getTools(): PluginTool[] {
875
1061
  return [
876
1062
  {
@@ -904,17 +1090,10 @@ export class HubActionsPlugin extends OraclePlugin {
904
1090
  effect: 'read',
905
1091
  handler: describeChainMessages,
906
1092
  },
907
- {
908
- name: 'request_chain_transaction',
909
- description: CHAIN_TRANSACTION_TOOL_DESCRIPTION,
910
- schema: chainTransactionSchema,
911
- effect: 'write',
912
- handler: requestChainTransaction,
913
- },
914
1093
  {
915
1094
  name: 'hub_action_status',
916
1095
  description:
917
- 'Read the verified status of a Hub action already prepared for this owner. Never executes.',
1096
+ 'Read the verified status of a Hub action already prepared for this owner. Never executes. A `cancelled` outcome was withdrawn before anything was sent, by the person or by Auth Hub (`meaning` says so): never say the person cancelled it.',
918
1097
  schema: statusSchema,
919
1098
  effect: 'read',
920
1099
  handler: hubActionStatus,