@priors/mcp 0.12.2 → 0.14.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.
@@ -0,0 +1,527 @@
1
+ // The work board's seam (docs/research/2026-10-23-hub-status/HUB-V1-SPEC.md 2.2 to 2.4, 3.1, 1.9 and 8 S0): the signed
2
+ // messages of paid requests and hire offers, the board's rules, the names of the bar and the states, the KV keys the
3
+ // board writes and the hub reads, and the grammar of Go mode's do= links. Frozen with the seam commit: every hub slice
4
+ // builds against these names, and a change goes through the integrator to every slice (spec 8, "Shared files").
5
+ //
6
+ // Seven messages, each an EIP-712 typed message in one domain, "Priors Work Board" 1 on chain 4663 (no verifying
7
+ // contract: nothing on chain checks them; the data Worker does, as the line board does with sdk/line-market.mjs's
8
+ // LineRequest, so a work message can never be read as one of the pool's or the line board's):
9
+ //
10
+ // WorkRequest signed by the client (any wallet, an EOA or an ERC-1271 account such as a Go mode account): the job,
11
+ // its budget (USDG units, 6 decimals), the deadline for the work, the bar an agent must pass, how long it
12
+ // stands open (expiry) and a salt. Its id is its EIP-712 hash.
13
+ // WorkTake signed by the agent's registry owner or its registry wallet (getAgentWallet): one agent asks to take a
14
+ // request. Its id is its EIP-712 hash.
15
+ // WorkAward signed by the client: the take it picks, and the address that will pay (never the worker's owner or
16
+ // wallet).
17
+ // WorkDeliver signed by the awarded agent's owner or registry wallet: a preview, the hash of the result and where to
18
+ // get it (an https address, or empty). The result itself is never stored.
19
+ // WorkReject signed by the client, after delivery and before payment: a reason (1 to 4), never free text.
20
+ // WorkCancel signed by the client, before delivery.
21
+ // HireOffer signed by the agent's registry owner or its registry wallet: its work for hire, per task or per minute,
22
+ // paid to its registry wallet. Its id is its EIP-712 hash.
23
+ //
24
+ // A paid request's receipt ({ tx }) is not signed: anyone posts it, and the data Worker reads that transaction (2.4).
25
+ //
26
+ // Nothing here signs, sends or reads the chain: the typed data is built for the signers' own wallets and keys (agents
27
+ // build theirs from this module; no hosted answer ever hands one out, spec 6.2). sdk/work-board.mjs (slice S3) checks
28
+ // each message: its fields, its time, its signer by ECDSA or ERC-1271, the bar and the caps, reusing sdk/line-market.mjs's
29
+ // signer helpers.
30
+ //
31
+ // The KV keys (written by data-worker/work-board.mjs, slice S3; read by data-worker/hub.mjs, slice S2):
32
+ //
33
+ // work:v1:req:<id> the board's whole record of one request: its messages, signatures, signers and times.
34
+ // Read by the board's own routes alone (GET /api/work/<id> is its view, WORK_VIEW_KEYS below).
35
+ // Kept until 30 days after the request closes.
36
+ // work:v1:open { v: 1, at, requests: [<a stored row>], paid: [{ id, agentId, at, x402, payer }] }: the
37
+ // open requests, as stored facts only (WORK_STORED_KEYS: a GET /api/work row without `state`
38
+ // and `act`), and the requests paid in the last 30 days, ids, worker, time, kind and payer
39
+ // only (each agent's requests.paid30: its x402 payments, one a payer). GET /api/work answers
40
+ // from it, and so do the hub's counts.requests and each agent's requests.open (the open
41
+ // requests that name it in forAgent).
42
+ // work:v1:offers { v: 1, at, offers: [<an OFFER_ENTRY>], hidden: [{ agentId, url, until }] }: every live
43
+ // signed hire offer, one line each (the hub's `hire` on each row, and counts.hire), and each
44
+ // agent's address Priors hid, where the hub shows no offer (a declared one included) until
45
+ // `until`.
46
+ // work:v1:offers:<agentId> { v: 1, offers: [<an OFFER_ENTRY>, plus offer (the HireOffer message), signature, signer,
47
+ // at] }: one agent's live offers in full (GET /api/hire-offers?agent=<id>).
48
+ // work:v1:client:<address> { v: 1, at, requests: [<a listed row>] }: every request the board still keeps that this
49
+ // client (lower case 0x address, workClientKey) posted, in any stage, newest first: every live
50
+ // one (open, awarded or delivered), then the newest of the others, WORK_RULES.listMax in all
51
+ // unless more are live (GET /api/work?client=<address>: a client's way back to its requests).
52
+ // work:v1:agent:<agentId> { v: 1, at, requests: [<a listed row>] }: the same for every request this agent asked to
53
+ // take (workAgentKey; GET /api/work?agent=<id>: a worker's way back to an awarded request).
54
+ // A listed row is a stored row plus `stage` (WORK_LISTED_KEYS), which says what a stored row
55
+ // cannot (a cancelled request); the answer works out `state` and `act` from it and drops it.
56
+ //
57
+ // A line of work:v1:offers also carries `wallet`, the registry wallet its offer was checked against (lower case), so the
58
+ // hub can leave out an offer whose agent has since lost or changed its registry wallet (a transfer clears it).
59
+ //
60
+ // The board's two spaces (WORK_SPACES): the test hosts (WORK_TEST_HOSTS: test, gotest and boardtest.priors.trade) keep
61
+ // their requests and offers apart from every other host's, so nothing posted while the board serves the test hosts alone
62
+ // can ever be listed, counted or capped on priors.trade once WORK_BOARD goes "on". The test hosts' space, "test", is the
63
+ // one the board has used since it was built: the board's object "work" and the keys above as they are. Every other host's,
64
+ // "live", has its own object ("work:live") and every key above with "live:" after "work:" (work:live:v1:open,
65
+ // work:live:v1:req:<id>, ...: workSpaceKey). Admin hides (POST /api/work/<id>/hide, POST /api/hire-offers/hide, behind
66
+ // the Worker secret WORK_ADMIN_TOKEN) act in the space of the host they are sent to.
67
+ //
68
+ // `state` and `act` are never stored: they depend on the clock and on the host that answers, and the one data Worker
69
+ // answers the test hosts and production alike. S2 and S3 compute them when they answer: `state` from the stored facts
70
+ // and the clock (a request past its expiry, or past its deadline plus WORK_RULES.graceS, has moved on even though KV
71
+ // still holds it until the next write; a row past its expiry is left out of GET /api/work and of every count), and
72
+ // `act` on the Go mode origin of the host that answers (go.priors.trade for priors.trade, gotest.priors.trade for the
73
+ // test hosts, as data-worker/line-options.mjs GO picks it).
74
+ //
75
+ // The POSTs' limit, 10 a network (an IPv4 address, or an IPv6 /64) in any 60 s, is the line board's own object
76
+ // (data-worker/line-market.mjs LINE_POST_LIMIT), named workPostKey(network), so the line board's count is untouched.
77
+ //
78
+ // The data Worker's two names for the board (data-worker/wrangler.jsonc, slice S2), never one: the switch WORK_BOARD
79
+ // (a var: "hosts", the hosts WORK_BOARD_HOSTS lists; "on"; anything else, off) and the Durable Object binding
80
+ // WORK_OBJECT (class WorkBoard, migration v5). Wrangler refuses a name bound twice, and env.WORK_BOARD must stay the
81
+ // switch's string for serves() to read; the line board keeps its own two apart the same way (LINE_MARKET, LINE_BOARD).
82
+ import { ethers } from "ethers";
83
+ import DEP from "../deployments/4663.v2.json" with { type: "json" };
84
+
85
+ export const CHAIN_ID = 4663;
86
+ /** USDG on Robinhood Chain: every budget, price and payment here is in it (6 decimals). */
87
+ export const USDG = DEP.usdg;
88
+
89
+ /** The board's EIP-712 domain: every work message and hire offer is signed in it. */
90
+ export const WORK_DOMAIN = Object.freeze({ name: "Priors Work Board", version: "1", chainId: CHAIN_ID });
91
+
92
+ /* ---- the typed data (spec 2.2 and 3.1, field for field) ---- */
93
+
94
+ export const WORK_REQUEST_TYPES = {
95
+ WorkRequest: [
96
+ { name: "client", type: "address" },
97
+ { name: "forAgent", type: "uint256" },
98
+ { name: "job", type: "string" },
99
+ { name: "title", type: "string" },
100
+ { name: "brief", type: "string" },
101
+ { name: "budget", type: "uint256" },
102
+ { name: "deadline", type: "uint64" },
103
+ { name: "bar", type: "uint8" },
104
+ { name: "expiry", type: "uint64" },
105
+ { name: "salt", type: "bytes32" },
106
+ ],
107
+ };
108
+ export const WORK_TAKE_TYPES = {
109
+ WorkTake: [
110
+ { name: "request", type: "bytes32" },
111
+ { name: "agentId", type: "uint256" },
112
+ { name: "salt", type: "bytes32" },
113
+ ],
114
+ };
115
+ export const WORK_AWARD_TYPES = {
116
+ WorkAward: [
117
+ { name: "request", type: "bytes32" },
118
+ { name: "take", type: "bytes32" },
119
+ { name: "payer", type: "address" },
120
+ ],
121
+ };
122
+ export const WORK_DELIVER_TYPES = {
123
+ WorkDeliver: [
124
+ { name: "request", type: "bytes32" },
125
+ { name: "preview", type: "string" },
126
+ { name: "resultHash", type: "bytes32" },
127
+ { name: "resultUrl", type: "string" },
128
+ ],
129
+ };
130
+ export const WORK_REJECT_TYPES = {
131
+ WorkReject: [
132
+ { name: "request", type: "bytes32" },
133
+ { name: "reason", type: "uint8" },
134
+ ],
135
+ };
136
+ export const WORK_CANCEL_TYPES = {
137
+ WorkCancel: [
138
+ { name: "request", type: "bytes32" },
139
+ ],
140
+ };
141
+ export const HIRE_OFFER_TYPES = {
142
+ HireOffer: [
143
+ { name: "agentId", type: "uint256" },
144
+ { name: "url", type: "string" },
145
+ { name: "unit", type: "uint8" },
146
+ { name: "price", type: "uint256" },
147
+ { name: "maxUnits", type: "uint16" },
148
+ { name: "expiry", type: "uint64" },
149
+ { name: "salt", type: "bytes32" },
150
+ ],
151
+ };
152
+
153
+ /** Each message's types, by its primary type. */
154
+ export const WORK_TYPES = Object.freeze({
155
+ WorkRequest: WORK_REQUEST_TYPES,
156
+ WorkTake: WORK_TAKE_TYPES,
157
+ WorkAward: WORK_AWARD_TYPES,
158
+ WorkDeliver: WORK_DELIVER_TYPES,
159
+ WorkReject: WORK_REJECT_TYPES,
160
+ WorkCancel: WORK_CANCEL_TYPES,
161
+ HireOffer: HIRE_OFFER_TYPES,
162
+ });
163
+ /** Who signs each message: "client" (the request's own `client`), or "agent" (the agent's registry owner or its
164
+ * registry wallet, getAgentWallet; for a WorkDeliver, the awarded agent's). */
165
+ export const WORK_SIGNED_BY = Object.freeze({
166
+ WorkRequest: "client", WorkTake: "agent", WorkAward: "client", WorkDeliver: "agent", WorkReject: "client", WorkCancel: "client", HireOffer: "agent",
167
+ });
168
+
169
+ /** Each POST and the message it carries, as `{ [key]: message, signature }` (the line board's `{ request, signature }`
170
+ * form): POST /api/work takes { request, signature }; POST /api/work/<id>/<step> takes { [step]: message, signature };
171
+ * POST /api/hire-offers takes { offer, signature }; POST /api/work/<id>/paid takes { tx }, unsigned. */
172
+ export const WORK_POSTS = Object.freeze({
173
+ request: { path: "/api/work", type: "WorkRequest" },
174
+ take: { path: "/api/work/<id>/take", type: "WorkTake" },
175
+ award: { path: "/api/work/<id>/award", type: "WorkAward" },
176
+ deliver: { path: "/api/work/<id>/deliver", type: "WorkDeliver" },
177
+ reject: { path: "/api/work/<id>/reject", type: "WorkReject" },
178
+ cancel: { path: "/api/work/<id>/cancel", type: "WorkCancel" },
179
+ offer: { path: "/api/hire-offers", type: "HireOffer" },
180
+ });
181
+
182
+ function typesOf(primaryType) {
183
+ const t = WORK_TYPES[primaryType];
184
+ if (!t) throw new Error(`no such work message: ${primaryType}`);
185
+ return t;
186
+ }
187
+ /** A message's EIP-712 typed data, for its signer's own wallet: { domain, types, primaryType, message }. The message is
188
+ * taken as it is written (uints as decimal strings or numbers, addresses, bytes32 as hex); sdk/work-board.mjs checks it. */
189
+ export const workTypedData = (primaryType, message) => ({ domain: { ...WORK_DOMAIN }, types: typesOf(primaryType), primaryType, message });
190
+ /** A message's EIP-712 hash: the id of a WorkRequest (a request's id), a WorkTake (a take's id, which a WorkAward names)
191
+ * and a HireOffer (an offer's id). */
192
+ export const workHash = (primaryType, message) => ethers.TypedDataEncoder.hash(WORK_DOMAIN, typesOf(primaryType), message).toLowerCase();
193
+
194
+ /* ---- the rules ---- */
195
+
196
+ const DAY = 86400;
197
+ /**
198
+ * Every limit of spec 2.2 and 3.1. Amounts in USDG units (6 decimals); times in unix seconds; text lengths in characters
199
+ * as Array.from counts them (code points). Every expiry and deadline is more than a minute ahead when it is posted (KV
200
+ * keeps nothing for less, as the line board's RULES.aheadS).
201
+ */
202
+ export const WORK_RULES = Object.freeze({
203
+ chainId: CHAIN_ID,
204
+ usdg: USDG,
205
+ decimals: 6,
206
+ aheadS: 60,
207
+ // a request (WorkRequest)
208
+ budgetMin: 1_000_000n, // 1 USDG
209
+ budgetMax: 20_000_000n, // 20 USDG
210
+ deadlineMaxS: 14 * DAY, // the deadline at most 14 days ahead; the expiry at most the deadline
211
+ titleMax: 80,
212
+ briefMax: 1000,
213
+ jobMax: 48, // a catalogue key or a seller job id (JOB_KEY), or empty
214
+ // a delivery (WorkDeliver)
215
+ previewMax: 500,
216
+ resultUrlMax: 200, // empty, or one https address
217
+ // the caps
218
+ openMax: 200, // open requests on the board, in all
219
+ openPerClient: 3,
220
+ takesPerRequest: 5, // and one take per agent
221
+ writesPerSignerDay: 20,
222
+ openPerNetwork: 3, // open requests posted from one network (an IPv4 address, or an IPv6 /64): ip_cap
223
+ takesPerOwner: 2, // takes on one request by the agents of one registry owner, or of one registry wallet: owner_takes
224
+ bodyBytes: 8192, // room for an ERC-6492 signature (a smart account not on chain yet) beside a brief in any script
225
+ postMax: 10, // POSTs per network (an IPv4 address or an IPv6 /64) in any postPeriodS seconds (LINE_POST_LIMIT)
226
+ postPeriodS: 60,
227
+ // after the deadline: a payment is taken until the deadline plus graceS, then a request with none (and no reject) is
228
+ // closed; everything is deleted keepS after it closes
229
+ graceS: 7 * DAY,
230
+ keepS: 30 * DAY,
231
+ // a hire offer (HireOffer)
232
+ offerMaxS: 30 * DAY, // then the owner signs again; maxUnits 0 withdraws it; a newer one for the agent and URL replaces it
233
+ hireMax: 20_000_000n, // price × maxUnits at most 20 USDG, and any one hire at most that
234
+ maxUnitsMax: 65535, // uint16
235
+ urlMax: 200,
236
+ offersPerAgent: 3, // live hire offers an agent holds (at as many URLs): offer_cap
237
+ offersMax: 1000, // live hire offers on the board, in all
238
+ // the lists of one client's and one agent's requests (work:v1:client:<address>, work:v1:agent:<agentId>): every live
239
+ // one, then the newest final ones up to listMax in all
240
+ listMax: 50,
241
+ // the offer's check at post (data-worker/reach.mjs's probe rules): one GET, no redirect, 5 s, 64 KB
242
+ probe: Object.freeze({ gets: 1, redirects: 0, timeoutMs: 5000, maxBytes: 65536 }),
243
+ });
244
+
245
+ /** A job key: a catalogue key ("research-brief") or a seller job id (16 hex), at most WORK_RULES.jobMax characters. */
246
+ export const JOB_KEY = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
247
+ export const isJobKey = (s) => typeof s === "string" && s.length <= WORK_RULES.jobMax && JOB_KEY.test(s);
248
+
249
+ /** The hire offer's unit: HireOffer.unit 1 is per task, 2 per minute; the API says "task" or "minute". */
250
+ export const HIRE_UNITS = Object.freeze({ task: 1, minute: 2 });
251
+ export const UNIT_NAMES = Object.freeze({ 1: "task", 2: "minute" });
252
+
253
+ /* ---- the bar, the reasons, the states ---- */
254
+
255
+ /**
256
+ * The bar a client sets (WorkRequest.bar), by number. Every bar also needs a registry wallet (where the agent gets paid)
257
+ * and no default. Read from the /api/check index and the Directory's reach facts.
258
+ * 0 any any ERC-8004 identity on chain 4663 (the default on test, so agents from other places can take work)
259
+ * 1 record a Priors record
260
+ * 2 line a line now
261
+ * 3 proven Proven or better (Score v2's rung 2 or more)
262
+ */
263
+ export const WORK_BARS = Object.freeze(["any", "record", "line", "proven"]);
264
+ export const BAR_DEFAULT = 0;
265
+ /** The bar in words, as the Jobs tab and the MCP say it. */
266
+ export const BAR_WORDS = Object.freeze([
267
+ "Open to any agent with a wallet and no default.",
268
+ "Open to agents with a record and no default.",
269
+ "Open to agents with a line now and no default.",
270
+ "Open to agents rated Proven or better, with a line now and no default.",
271
+ ]);
272
+
273
+ /** A WorkReject's reason, by number (0 is no reason, never taken). No free text. */
274
+ export const REJECT_REASONS = Object.freeze([null, "not_delivered", "not_asked", "late", "other"]);
275
+ export const REJECT_WORDS = Object.freeze([null, "Not delivered", "Not what was asked", "Late", "Other"]);
276
+
277
+ /**
278
+ * A request's states. Open until awarded, cancelled or past its expiry (expired: no award before it). Awarded, then
279
+ * delivered; then paid (a receipt, 2.4), rejected (after delivery, before payment), or closed (no payment and no reject
280
+ * by the deadline plus WORK_RULES.graceS: shown "Closed, not paid" on the request alone). Cancelled by the client before
281
+ * delivery. A receipt after the award closes it paid even before delivery. In v0 no state marks either party's record.
282
+ */
283
+ export const WORK_STATES = Object.freeze(["open", "awarded", "delivered", "paid", "rejected", "cancelled", "expired", "closed"]);
284
+ export const WORK_FINAL = Object.freeze(["paid", "rejected", "cancelled", "expired", "closed"]);
285
+ /** The states each state can move to (a final state moves to none). */
286
+ export const WORK_NEXT = Object.freeze({
287
+ open: Object.freeze(["awarded", "cancelled", "expired"]),
288
+ awarded: Object.freeze(["delivered", "paid", "cancelled", "closed"]),
289
+ delivered: Object.freeze(["paid", "rejected", "closed"]),
290
+ paid: Object.freeze([]), rejected: Object.freeze([]), cancelled: Object.freeze([]), expired: Object.freeze([]), closed: Object.freeze([]),
291
+ });
292
+
293
+ /* ---- the KV keys ---- */
294
+
295
+ export const WORK_OPEN_KEY = "work:v1:open";
296
+ export const WORK_OFFERS_KEY = "work:v1:offers";
297
+ const BYTES32 = /^0x[0-9a-fA-F]{64}$/;
298
+ const AGENT_ID = /^(?:0|[1-9][0-9]{0,11})$/;
299
+ /** A request's key, work:v1:req:<id> (the id in lower case). */
300
+ export function workReqKey(id) {
301
+ if (typeof id !== "string" || !BYTES32.test(id)) throw new Error("a request id is 32 bytes of hex");
302
+ return `work:v1:req:${id.toLowerCase()}`;
303
+ }
304
+ /** One agent's offers' key, work:v1:offers:<agentId> (the id in decimal). */
305
+ export function workOffersKey(agentId) {
306
+ const s = typeof agentId === "number" && Number.isSafeInteger(agentId) ? String(agentId) : typeof agentId === "bigint" ? agentId.toString() : agentId;
307
+ if (typeof s !== "string" || !AGENT_ID.test(s)) throw new Error("an agent id is a whole number, in decimal");
308
+ return `work:v1:offers:${s}`;
309
+ }
310
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
311
+ /** One client's requests' key, work:v1:client:<address> (the address in lower case). */
312
+ export function workClientKey(address) {
313
+ if (typeof address !== "string" || !ADDRESS.test(address)) throw new Error("a client is a 0x address of 40 hex");
314
+ return `work:v1:client:${address.toLowerCase()}`;
315
+ }
316
+ /** One agent's requests' key (the requests it asked to take), work:v1:agent:<agentId> (the id in decimal). */
317
+ export function workAgentKey(agentId) {
318
+ const s = typeof agentId === "number" && Number.isSafeInteger(agentId) ? String(agentId) : typeof agentId === "bigint" ? agentId.toString() : agentId;
319
+ if (typeof s !== "string" || !AGENT_ID.test(s)) throw new Error("an agent id is a whole number, in decimal");
320
+ return `work:v1:agent:${s}`;
321
+ }
322
+ /** The hosts of the board's "test" space; every other host is in the "live" space (see the KV keys above). */
323
+ export const WORK_TEST_HOSTS = Object.freeze(["test.priors.trade", "gotest.priors.trade", "boardtest.priors.trade"]);
324
+ export const WORK_SPACES = Object.freeze(["test", "live"]);
325
+ /** The board's space for a request's host name: "test" for WORK_TEST_HOSTS, "live" for every other host. */
326
+ export const workSpaceOf = (hostname) => (WORK_TEST_HOSTS.includes(String(hostname || "").toLowerCase().replace(/\.$/, "")) ? "test" : "live");
327
+ /** A board key (any of the above) in `space`: as it is in "test", with "live:" after "work:" in "live". */
328
+ export function workSpaceKey(space, key) {
329
+ if (!WORK_SPACES.includes(space)) throw new Error("the board's space is test or live");
330
+ if (typeof key !== "string" || !key.startsWith("work:v1:")) throw new Error("a board key starts work:v1:");
331
+ return space === "live" ? `work:live:${key.slice(5)}` : key;
332
+ }
333
+ /** The name of a network's count in the line board's per-IP object (LINE_POST_LIMIT.idFromName), work:<network> (the
334
+ * data Worker's networkOf: an IPv4 address, or an IPv6 /64). */
335
+ export const workPostKey = (ip) => `work:${ip == null || ip === "" ? "unknown" : String(ip)}`;
336
+
337
+ /** The board's switch, env.WORK_BOARD (with WORK_BOARD_HOSTS): serves(env, WORK_SWITCH, url). */
338
+ export const WORK_SWITCH = "WORK_BOARD";
339
+ /** The board's Durable Object binding, env.WORK_OBJECT (class WorkBoard extends WorkBoardBase, migration v5). */
340
+ export const WORK_OBJECT = "WORK_OBJECT";
341
+
342
+ /* ---- amounts ---- */
343
+
344
+ /** USDG units (6 decimals) as the hub's answers write them: exact, with at least two decimals ("0.10", "120.00",
345
+ * "0.025", "1.234567"). */
346
+ export function usdgText(units) {
347
+ const n = BigInt(units);
348
+ if (n < 0n) throw new Error("a USDG amount is never negative");
349
+ const whole = n / 1_000_000n, frac = (n % 1_000_000n).toString().padStart(6, "0").replace(/0+$/, "");
350
+ return `${whole}.${frac.padEnd(2, "0")}`;
351
+ }
352
+ /** A written USDG amount ("0.10") as USDG units (100000n), or an Error for anything else. */
353
+ export function usdgUnits(text) {
354
+ const m = /^(0|[1-9][0-9]{0,15})(?:\.([0-9]{1,6}))?$/.exec(String(text));
355
+ if (!m) throw new Error("a USDG amount is written like 0.10 (at most 6 decimals)");
356
+ return BigInt(m[1]) * 1_000_000n + BigInt((m[2] || "").padEnd(6, "0"));
357
+ }
358
+
359
+ /* ---- hire offers, as the board keeps them and the hub shows them ---- */
360
+
361
+ /** The keys of one line of work:v1:offers (OFFER_ENTRY), in order. */
362
+ export const OFFER_ENTRY_KEYS = Object.freeze(["offerId", "agentId", "url", "host", "unit", "price", "maxUnits", "expiry"]);
363
+ /**
364
+ * One line of work:v1:offers, from a verified HireOffer message: { offerId, agentId, url, host, unit ("task" or
365
+ * "minute"), price (USDG, written: "0.10"), maxUnits, expiry }.
366
+ */
367
+ export function offerEntryOf(message) {
368
+ const unit = UNIT_NAMES[Number(message.unit)];
369
+ if (!unit) throw new Error("a hire offer's unit is 1 (per task) or 2 (per minute)");
370
+ return {
371
+ offerId: workHash("HireOffer", message), agentId: Number(message.agentId), url: String(message.url), host: new URL(String(message.url)).hostname,
372
+ unit, price: usdgText(message.price), maxUnits: Number(message.maxUnits), expiry: Number(message.expiry),
373
+ };
374
+ }
375
+ /** The keys of one `hire` item on a /api/hub row (spec 6.1), in order. */
376
+ export const HIRE_ITEM_KEYS = Object.freeze(["offer", "unit", "price", "maxUnits", "host", "source"]);
377
+ /** A /api/hub row's `hire` item: from an OFFER_ENTRY (source "signed": `offer` its id), or from a declared offer the
378
+ * Directory's reach facts read (source "declared": `offer` and `maxUnits` null). */
379
+ export function hireItemOf(entry, source = "signed") {
380
+ if (source !== "signed" && source !== "declared") throw new Error("a hire offer's source is signed or declared");
381
+ return {
382
+ offer: source === "signed" ? entry.offerId : null, unit: entry.unit, price: entry.price,
383
+ maxUnits: source === "signed" ? entry.maxUnits : null, host: entry.host, source,
384
+ };
385
+ }
386
+
387
+ /* ---- what GET /api/work answers ---- */
388
+
389
+ /**
390
+ * The keys of a request as GET /api/work/<id> gives it (spec 6.1), in order. The spec's fields, plus three it needs to
391
+ * say its own states: `expiry` (open until then), `at` (when it was posted) and `reject` ({ reason } or null).
392
+ * id, client (lower case), forAgent (0: every agent), job, title, brief, budget (USDG, written), deadline, expiry,
393
+ * bar, state, at, takes: [{ id, agentId, at }], award: { take, agentId, payer, at } | null,
394
+ * delivery: { preview, resultHash, resultUrl } | null, reject: { reason } | null, paid: { tx, x402 } | null,
395
+ * act: { take } (Go mode's do=take link while the request is open, awarded or delivered: that one screen shows Take to
396
+ * an agent's owner, Deliver to the awarded agent's, and Award, Reject and Cancel to the client; null once final)
397
+ * Each take's `id` is its WorkTake's EIP-712 hash (workHash("WorkTake", message)): the bytes32 a client's WorkAward names
398
+ * as `take`, so a client builds its award from this answer alone; `award.take` is always one of them. The WorkTake
399
+ * message itself (its salt) is never served.
400
+ * A row of GET /api/work ({ v, at, n, requests }: the open requests, newest first) is the same without `brief`.
401
+ */
402
+ export const WORK_VIEW_KEYS = Object.freeze(["id", "client", "forAgent", "job", "title", "brief", "budget", "deadline", "expiry", "bar", "state", "at", "takes", "award", "delivery", "reject", "paid", "act"]);
403
+ export const WORK_ROW_KEYS = Object.freeze(WORK_VIEW_KEYS.filter((k) => k !== "brief"));
404
+ /** The keys of a take in a request's `takes`, in order. */
405
+ export const WORK_TAKE_KEYS = Object.freeze(["id", "agentId", "at"]);
406
+ /** The keys of a row as work:v1:open stores it: a GET /api/work row without `state` and `act`, which are computed when
407
+ * the board answers (see the KV keys above). */
408
+ export const WORK_STORED_KEYS = Object.freeze(WORK_ROW_KEYS.filter((k) => k !== "state" && k !== "act"));
409
+ /** The keys of a row of one client's or one agent's list (work:v1:client:<address>, work:v1:agent:<agentId>): a stored
410
+ * row and its `stage` (sdk/work-board.mjs stageOf: open, awarded, delivered, paid, rejected or cancelled), from which
411
+ * GET /api/work?client= and ?agent= work out its `state` at the clock. */
412
+ export const WORK_LISTED_KEYS = Object.freeze([...WORK_STORED_KEYS, "stage"]);
413
+
414
+ /* ---- Go mode's do= links (spec 1.9) ---- */
415
+
416
+ /** Go mode's origins: production's and the test host's. */
417
+ export const GO_ORIGINS = Object.freeze(["https://go.priors.trade", "https://gotest.priors.trade"]);
418
+ export const GO_PATH = "/account";
419
+ /**
420
+ * Each verb, what it needs and what it may carry. No amount ever travels in a link (prices are read again in Go mode),
421
+ * and there is no rent, borrow or repay verb. A link Priors builds carries agent, do, req, job, offer, bid and origin
422
+ * only, each at most once.
423
+ * hire agent, offer? the Hire sheet for that agent's offer
424
+ * buy agent the Buy sheet (read only, "not open yet", while the market has no address)
425
+ * sell agent?, bid? the Sell checklist for the account's own agent (no agent: Go mode asks which of the
426
+ * account's agents to sell, as the For sale empty state's [Sell an agent] opens it, spec 1.7;
427
+ * bid: that bid first among the ones that can take it, to accept)
428
+ * offer agent? "List its work": sign a hire offer
429
+ * post agent? post a job (with agent: a request for that agent only)
430
+ * take req, agent? take a paid request with one of the account's agents (agent: the one to take it with)
431
+ * job job that job's sheet in Jobs
432
+ * bid agent make a bid on that agent (its amount typed in Go mode, never carried)
433
+ * bidany origin make a bid on any one agent of that origin (its key, as the Directory's ?origin= writes it)
434
+ * bids the account's own bids
435
+ * share agent set a builder share on the account's own agent (its rate typed in Go mode, never carried;
436
+ * it pays the account itself)
437
+ * shares the builder shares that pay the account (Lower, Change address)
438
+ * handover agent what a sale hands over: Make it yours for its owner, After the sale for a former owner (a
439
+ * key or a wallet is made or read in Go mode, never carried)
440
+ */
441
+ export const GO_VERBS = Object.freeze({
442
+ hire: Object.freeze({ need: ["agent"], may: ["offer"] }),
443
+ buy: Object.freeze({ need: ["agent"], may: [] }),
444
+ sell: Object.freeze({ need: [], may: ["agent", "bid"] }),
445
+ offer: Object.freeze({ need: [], may: ["agent"] }),
446
+ post: Object.freeze({ need: [], may: ["agent"] }),
447
+ take: Object.freeze({ need: ["req"], may: ["agent"] }),
448
+ job: Object.freeze({ need: ["job"], may: [] }),
449
+ bid: Object.freeze({ need: ["agent"], may: [] }),
450
+ bidany: Object.freeze({ need: ["origin"], may: [] }),
451
+ bids: Object.freeze({ need: [], may: [] }),
452
+ share: Object.freeze({ need: ["agent"], may: [] }),
453
+ shares: Object.freeze({ need: [], may: [] }),
454
+ handover: Object.freeze({ need: ["agent"], may: [] }),
455
+ });
456
+ /** The parameters, in the order a link writes them (bid and origin last: every link of before keeps its one form). */
457
+ export const GO_PARAMS = Object.freeze(["agent", "do", "req", "job", "offer", "bid", "origin"]);
458
+ const GO_ID = /^(?:0|[1-9][0-9]{0,9})$/; // the board's ids (web/board-core.js ID), in their one written form
459
+ const GO_BID = /^[1-9][0-9]{0,19}$/; // a bid's id on AgentMarketV2 (counted from 1), in its one written form
460
+ const GO_ORIGIN = /^[a-z0-9-]{1,24}$/; // an origin's key (data-worker/origins.mjs KEY), as the Directory's ?origin= has it
461
+ const GO_FORMS = { agent: (v) => GO_ID.test(v), req: (v) => BYTES32.test(v), offer: (v) => BYTES32.test(v), job: isJobKey, bid: (v) => GO_BID.test(v), origin: (v) => GO_ORIGIN.test(v) };
462
+
463
+ /**
464
+ * The do= link's own fields, checked: { verb, agent, req, job, offer } (each absent one null; hex in lower case), plus
465
+ * `bid` and `originKey` (origin= read) only when the link carries them, so every link of before reads exactly as it
466
+ * did; or { error }. `params` is a URLSearchParams or a query string ("?agent=1234&do=hire"). The origin's key is read
467
+ * as `originKey` because a whole link's `origin` is Go mode's own (parseGoLink).
468
+ *
469
+ * Two uses, one rule each. Go mode reads its own address with it as it is (the default): only the seven keys are read,
470
+ * each at most once and well formed, and every other key is left alone, because Go mode's address carries others next
471
+ * to a do= link (Privy's privy_oauth_code, privy_oauth_state and privy_oauth_provider after a Google sign-in, which come
472
+ * back on the query the link brought; the rig's rig=1). An amount, a price or any other key is never read, so it never
473
+ * reaches a sheet. With { strict: true }, as goLink and parseGoLink check the links Priors builds, a key outside the
474
+ * seven refuses the whole link.
475
+ */
476
+ export function parseGoQuery(params, { strict = false } = {}) {
477
+ const p = params instanceof URLSearchParams ? params : new URLSearchParams(String(params || "").replace(/^\?/, ""));
478
+ const one = {};
479
+ for (const k of new Set(p.keys())) {
480
+ if (!GO_PARAMS.includes(k)) {
481
+ if (strict) return { error: `a Go mode link carries no ${k}` };
482
+ continue;
483
+ }
484
+ const all = p.getAll(k);
485
+ if (all.length > 1) return { error: `${k} is sent once` };
486
+ one[k] = all[0];
487
+ }
488
+ if (one.do == null) return { error: "no do" };
489
+ const verb = one.do;
490
+ if (!Object.prototype.hasOwnProperty.call(GO_VERBS, verb)) return { error: `no such verb: ${verb}` };
491
+ const rule = GO_VERBS[verb];
492
+ for (const k of rule.need) if (one[k] == null) return { error: `${verb} needs ${k}` };
493
+ const out = { verb, agent: null, req: null, job: null, offer: null };
494
+ for (const k of ["agent", "req", "job", "offer", "bid", "origin"]) {
495
+ if (one[k] == null) continue;
496
+ if (!rule.need.includes(k) && !rule.may.includes(k)) return { error: `${verb} takes no ${k}` };
497
+ if (!GO_FORMS[k](one[k])) return { error: `${k} is not well formed` };
498
+ out[k === "origin" ? "originKey" : k] = k === "req" || k === "offer" ? one[k].toLowerCase() : one[k];
499
+ }
500
+ return out;
501
+ }
502
+
503
+ /** A whole do= link as Priors builds it, checked: https, one of `origins`, the path /account, no user, no hash (a hash
504
+ * does not survive the sign-in), then its query (parseGoQuery, strict: no key outside the seven, unless
505
+ * { strict: false }). { verb, agent, req, job, offer, origin } (`origin`: Go mode's, the link's own), with `bid` and
506
+ * `originKey` when it carries them, or { error }. */
507
+ export function parseGoLink(link, { origins = GO_ORIGINS, strict = true } = {}) {
508
+ let u;
509
+ try { u = new URL(String(link)); } catch { return { error: "not a link" }; }
510
+ if (u.protocol !== "https:") return { error: "not https" };
511
+ if (!origins.includes(u.origin)) return { error: `not Go mode's origin: ${u.origin}` };
512
+ if (u.username || u.password) return { error: "a link carries no user" };
513
+ if (u.pathname !== GO_PATH) return { error: `Go mode's path is ${GO_PATH}` };
514
+ if (String(link).includes("#")) return { error: "a link carries no hash" };
515
+ const q = parseGoQuery(u.searchParams, { strict });
516
+ return q.error ? q : { ...q, origin: u.origin };
517
+ }
518
+
519
+ /** The do= link for `verb` on Go mode's origin `app`: {app}/account?agent=..&do=..&req=..&job=..&offer=..&bid=..
520
+ * &origin=.., or null when the origin is not https or the fields do not make a link parseGoQuery takes strictly. The
521
+ * fields are what parseGoQuery reads back (`originKey` is written origin=). Never an amount. */
522
+ export function goLink(app, verb, { agent = null, req = null, job = null, offer = null, bid = null, originKey = null } = {}) {
523
+ if (typeof app !== "string" || !/^https:\/\/[a-z0-9.-]+(?::[0-9]{1,5})?$/.test(app)) return null;
524
+ const v = { agent: agent == null ? null : String(agent), do: verb, req, job, offer, bid: bid == null ? null : String(bid), origin: originKey };
525
+ const q = GO_PARAMS.filter((k) => v[k] != null).map((k) => `${k}=${encodeURIComponent(k === "req" || k === "offer" ? String(v[k]).toLowerCase() : v[k])}`).join("&");
526
+ return parseGoQuery(q, { strict: true }).error ? null : `${app}${GO_PATH}?${q}`;
527
+ }