@sjawhar/pi-envoy 15.0.1 → 15.0.3

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.
package/dist/dispatch.js CHANGED
@@ -15957,7 +15957,8 @@ function fieldKinds(spec) {
15957
15957
  nullable,
15958
15958
  required: required.has(field),
15959
15959
  ...description === undefined ? {} : { description },
15960
- ...values === undefined ? {} : { values }
15960
+ ...values === undefined ? {} : { values },
15961
+ shape: inner === undefined ? [] : shapeLines(inner, "")
15961
15962
  });
15962
15963
  }
15963
15964
  return fields;
@@ -15992,6 +15993,58 @@ function kindOf(field, node) {
15992
15993
  return "json";
15993
15994
  }
15994
15995
  }
15996
+ function withoutNull(node) {
15997
+ const members = (node.anyOf ?? [node]).filter((member) => member.type !== "null");
15998
+ return members.length === 1 ? members[0] : undefined;
15999
+ }
16000
+ function typeName(node) {
16001
+ if (node.anyOf !== undefined)
16002
+ return node.anyOf.map(typeName).join(" or ");
16003
+ if (node.enum !== undefined)
16004
+ return node.enum.map(String).join("|");
16005
+ switch (node.type) {
16006
+ case "string":
16007
+ return "text";
16008
+ case "integer":
16009
+ case "number":
16010
+ case "boolean":
16011
+ case "null":
16012
+ return node.type;
16013
+ case "object":
16014
+ return "object";
16015
+ case "array":
16016
+ return node.items === undefined ? "list" : `list of ${pluralTypeName(node.items)}`;
16017
+ default:
16018
+ return "any JSON";
16019
+ }
16020
+ }
16021
+ function pluralTypeName(node) {
16022
+ if (node.type === "object")
16023
+ return "objects";
16024
+ if (node.type === "integer")
16025
+ return "integers";
16026
+ if (node.type === "number")
16027
+ return "numbers";
16028
+ return typeName(node);
16029
+ }
16030
+ function shapeLines(node, indent) {
16031
+ const item = node.type === "array" ? node.items : undefined;
16032
+ const properties = (item ?? node).properties;
16033
+ if (properties === undefined)
16034
+ return [];
16035
+ const required = new Set((item ?? node).required ?? []);
16036
+ return [
16037
+ `${indent}${item === undefined ? "Its keys:" : "Each item's keys:"}`,
16038
+ ...Object.entries(properties).flatMap(([key, child]) => {
16039
+ const about = [required.has(key) ? "required" : undefined, typeName(child)].filter((part) => part !== undefined).join("; ");
16040
+ const inner = withoutNull(child);
16041
+ return [
16042
+ `${indent} ${key} (${about})${child.description === undefined ? "" : `: ${child.description}`}`,
16043
+ ...inner === undefined ? [] : shapeLines(inner, `${indent} `)
16044
+ ];
16045
+ })
16046
+ ];
16047
+ }
15995
16048
  function singular(field) {
15996
16049
  return field.endsWith("s") ? field.slice(0, -1) : field;
15997
16050
  }
@@ -16039,10 +16092,17 @@ function flagTable(tool, fields) {
16039
16092
  field,
16040
16093
  action: "json",
16041
16094
  value: "<json>",
16042
- text: `Every option as a JSON list of {label, description?}, in place of --${singular(name)}.`
16095
+ text: [`Every option as a JSON list, in place of --${singular(name)}.`, ...info.shape].join(`
16096
+ `)
16043
16097
  });
16044
16098
  } else if (kind === "json") {
16045
- add(`--${name}-json`, { field, action: "json", value: "<json>", text: about });
16099
+ add(`--${name}-json`, {
16100
+ field,
16101
+ action: "json",
16102
+ value: "<json>",
16103
+ text: [about, ...info.shape].filter((line) => line !== "").join(`
16104
+ `)
16105
+ });
16046
16106
  add(`--${name}-json-file`, {
16047
16107
  field,
16048
16108
  action: "json-file",
@@ -16320,7 +16380,8 @@ function commandHelp(tool) {
16320
16380
  surface.spec.description,
16321
16381
  "",
16322
16382
  "Flags:",
16323
- ...commandFlagTable(tool).flatMap((row) => row.text === "" ? [` ${row.flag}`] : [` ${row.flag}`, ` ${row.text}`]),
16383
+ ...commandFlagTable(tool).flatMap((row) => row.text === "" ? [` ${row.flag}`] : [` ${row.flag}`, ...row.text.split(`
16384
+ `).map((line) => ` ${line}`)]),
16324
16385
  "",
16325
16386
  `Example: ${commandLine(tool, surface.spec.example)}`,
16326
16387
  ""
@@ -19089,16 +19150,11 @@ function artifactByReference(artifacts, artifactReference, owner, canonical) {
19089
19150
  const byId = artifacts.find((candidate) => candidate.id === artifactReference);
19090
19151
  if (byId !== undefined)
19091
19152
  return byId;
19092
- const byName = artifacts.filter((candidate) => candidate.name === artifactReference);
19093
- if (bySlug !== undefined) {
19094
- const named = byName.filter((candidate) => candidate.id !== bySlug.id && candidate.kind === "doc");
19095
- if (named.length > 0) {
19096
- throw new Error(documentReferenceProblem(artifactReference, [bySlug, ...named], owner, "id"));
19097
- }
19153
+ if (bySlug !== undefined)
19098
19154
  return bySlug;
19099
- }
19155
+ const byName = artifacts.filter((candidate) => candidate.name === artifactReference);
19100
19156
  if (byName.length > 1) {
19101
- throw new Error(documentReferenceProblem(artifactReference, byName, owner, "slug"));
19157
+ throw new Error(documentReferenceProblem(artifactReference, byName, owner, true));
19102
19158
  }
19103
19159
  const [artifact] = byName;
19104
19160
  if (artifact === undefined) {
@@ -19153,10 +19209,10 @@ async function documentTargets(client, resolution) {
19153
19209
  };
19154
19210
  }
19155
19211
  var documentHintLimit = 8;
19156
- function documentReferenceProblem(reference, documents, owner, use) {
19157
- const hints = documents.slice(0, documentHintLimit).map((document) => use === "id" ? `${document.id} (${document.slug}, ${document.name})` : `${document.slug} (${document.name})`);
19212
+ function documentReferenceProblem(reference, documents, owner, ambiguous = false) {
19213
+ const hints = documents.slice(0, documentHintLimit).map((document) => `${document.slug} (${document.name})`);
19158
19214
  const list = hints.length === 0 ? "none" : hints.join(", ");
19159
- return use === undefined ? `document "${reference}" not found by slug; this ${owner}'s documents: ${list}` : `"${reference}" names ${documents.length} documents on this ${owner}; use ${use === "id" ? "the id" : "a slug"}: ${list}`;
19215
+ return ambiguous ? `"${reference}" names ${documents.length} documents on this ${owner}; use a slug: ${list}` : `document "${reference}" not found by slug; this ${owner}'s documents: ${list}`;
19160
19216
  }
19161
19217
  var askHintLimit = 8;
19162
19218
  function askIDInputProblem(asks, scope) {
@@ -21987,7 +22043,8 @@ var ErrorWireSchema = object({
21987
22043
  });
21988
22044
  var EnvelopeResponseSchema = EnvelopeSchema.extend({
21989
22045
  recipient: string2().optional(),
21990
- holder: string2().optional()
22046
+ holder: string2().optional(),
22047
+ duplicate: boolean2().optional()
21991
22048
  });
21992
22049
  var ReplayWireSchema = object({
21993
22050
  stream: object({
@@ -22059,44 +22116,84 @@ class EnvoyApiError extends Error {
22059
22116
  this.code = parsed?.code;
22060
22117
  }
22061
22118
  }
22119
+ var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
22120
+
22121
+ class EnvoySendUnconfirmedError extends Error {
22122
+ targetSessionID;
22123
+ idempotencyKey;
22124
+ attempts;
22125
+ last;
22126
+ name = "EnvoySendUnconfirmedError";
22127
+ resendSafe;
22128
+ constructor(targetSessionID, idempotencyKey, attempts, last) {
22129
+ const got = last instanceof EnvoyApiError ? `the listener answered ${last.details.status} (${last.message})` : `the listener did not answer (${last instanceof Error ? last.message : String(last)})`;
22130
+ const tried = attempts === 1 ? "on its only attempt" : `on the last of ${attempts} attempts`;
22131
+ const resendSafe = mintedDedupeKey2.test(`agent.${targetSessionID.trim()}.${idempotencyKey}`);
22132
+ const resend = resendSafe ? `Sending it again with idempotency_key ${idempotencyKey} within ` + `${DELIVERY_DUPLICATE_WINDOW_MS / 3600000} hours is the safe resend: Envoy drops it as ` + "a repeat if the first copy arrived (a recipient that restarted in between can rarely " + "see it twice)." : `Envoy cannot recognise a resend under idempotency_key ${idempotencyKey} as a repeat ` + "(the key is not a lower-case UUID, or the session id holds a dot): ask the recipient " + "whether it arrived before sending it again.";
22133
+ super(`The send to ${targetSessionID} is not confirmed delivered: ${got} ${tried}. It may or may ` + `not have arrived. ${resend}`, { cause: last });
22134
+ this.targetSessionID = targetSessionID;
22135
+ this.idempotencyKey = idempotencyKey;
22136
+ this.attempts = attempts;
22137
+ this.last = last;
22138
+ this.resendSafe = resendSafe;
22139
+ }
22140
+ }
22062
22141
  function createEnvoyClient(config) {
22063
22142
  const baseUrl = normalizeEnvoyUrl(config.baseUrl);
22064
22143
  const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
22065
22144
  const apiToken = config.token;
22145
+ const attempts = config.retry === false ? 1 : 2;
22146
+ const attemptOnce = async (url, init, deadlineMs) => {
22147
+ const headers = new Headers(init.headers);
22148
+ if (apiToken)
22149
+ headers.set("Authorization", `Bearer ${apiToken}`);
22150
+ let response;
22151
+ try {
22152
+ response = await config.fetch(url, {
22153
+ ...init,
22154
+ headers,
22155
+ signal: AbortSignal.timeout(deadlineMs)
22156
+ });
22157
+ } catch (error) {
22158
+ return { unanswered: error };
22159
+ }
22160
+ try {
22161
+ return { response, body: await response.text() };
22162
+ } catch (error) {
22163
+ if (response.status >= 400 && response.status < 500) {
22164
+ return { response, body: `(its body did not arrive: ${String(error)})` };
22165
+ }
22166
+ return { unanswered: error };
22167
+ }
22168
+ };
22066
22169
  const request = async (path, init, options = {}) => {
22067
22170
  const url = `${baseUrl}${path}`;
22068
- const attempts = config.retry === false ? 1 : 2;
22069
22171
  const tries = options.retry === false ? 1 : attempts;
22070
22172
  for (let attempt = 0;attempt < tries; attempt += 1) {
22071
- let response;
22072
- try {
22073
- const headers = new Headers(init.headers);
22074
- if (apiToken)
22075
- headers.set("Authorization", `Bearer ${apiToken}`);
22076
- response = await config.fetch(url, {
22077
- ...init,
22078
- headers,
22079
- signal: AbortSignal.timeout(options.timeoutMs ?? timeoutMs)
22080
- });
22081
- } catch (error) {
22173
+ const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs);
22174
+ if ("unanswered" in outcome) {
22175
+ options.onUnanswered?.();
22082
22176
  if (attempt + 1 < tries) {
22083
22177
  await waitForRetry();
22084
22178
  continue;
22085
22179
  }
22086
- throw error;
22180
+ throw outcome.unanswered;
22087
22181
  }
22088
- const responseBody = await response.text();
22182
+ const { response, body } = outcome;
22089
22183
  if (response.ok)
22090
- return responseBody;
22184
+ return body;
22091
22185
  const error = new EnvoyApiError({
22092
22186
  method: init.method ?? "GET",
22093
22187
  url,
22094
22188
  status: response.status,
22095
- responseBody
22189
+ responseBody: body
22096
22190
  });
22097
- if (response.status >= 500 && attempt + 1 < tries) {
22098
- await waitForRetry();
22099
- continue;
22191
+ if (response.status >= 500) {
22192
+ options.onUnanswered?.();
22193
+ if (attempt + 1 < tries) {
22194
+ await waitForRetry();
22195
+ continue;
22196
+ }
22100
22197
  }
22101
22198
  throw error;
22102
22199
  }
@@ -22132,18 +22229,33 @@ function createEnvoyClient(config) {
22132
22229
  getInterest: async (sessionID) => InterestWireSchema.parse(JSON.parse(await request(`/v1/interests/${sessionID}`, {}))),
22133
22230
  send: async (input) => {
22134
22231
  const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
22135
- const response = EnvelopeResponseSchema.parse(JSON.parse(await post("/v1/messages/send", {
22136
- source: input.source ?? "agent",
22137
- ...sourceSession(input.sourceSessionID),
22138
- target_session: input.targetSessionID,
22139
- message: input.message,
22140
- idempotency_key: idempotencyKey,
22141
- ...messageMetadata(input)
22142
- })));
22232
+ let unanswered = false;
22233
+ let response;
22234
+ try {
22235
+ const answer = await post("/v1/messages/send", {
22236
+ source: input.source ?? "agent",
22237
+ ...sourceSession(input.sourceSessionID),
22238
+ target_session: input.targetSessionID,
22239
+ message: input.message,
22240
+ idempotency_key: idempotencyKey,
22241
+ ...messageMetadata(input)
22242
+ }, {
22243
+ onUnanswered: () => {
22244
+ unanswered = true;
22245
+ }
22246
+ });
22247
+ response = EnvelopeResponseSchema.parse(JSON.parse(answer));
22248
+ } catch (error) {
22249
+ if (error instanceof EnvoyApiError && error.details.status < 500 && !unanswered) {
22250
+ throw error;
22251
+ }
22252
+ throw new EnvoySendUnconfirmedError(input.targetSessionID, idempotencyKey, attempts, error);
22253
+ }
22143
22254
  return {
22144
22255
  envelope: response,
22145
22256
  recipient: response.recipient ?? input.targetSessionID,
22146
- confirmed: response.recipient !== undefined
22257
+ confirmed: response.recipient !== undefined,
22258
+ duplicate: response.duplicate === true
22147
22259
  };
22148
22260
  },
22149
22261
  publish: async (input) => {
@@ -22182,7 +22294,13 @@ function createEnvoyClient(config) {
22182
22294
  raw = await post("/v1/roles/set", body);
22183
22295
  } catch (error) {
22184
22296
  if (error instanceof EnvoyApiError && error.details.status === 409) {
22185
- const held = RoleHeldWireSchema.safeParse(JSON.parse(error.details.responseBody));
22297
+ let answer;
22298
+ try {
22299
+ answer = JSON.parse(error.details.responseBody);
22300
+ } catch {
22301
+ throw error;
22302
+ }
22303
+ const held = RoleHeldWireSchema.safeParse(answer);
22186
22304
  if (held.success)
22187
22305
  return { claimed: false, holder: held.data.holder };
22188
22306
  }
package/dist/envoy.js CHANGED
@@ -31747,7 +31747,8 @@ function fieldKinds(spec) {
31747
31747
  nullable,
31748
31748
  required: required.has(field),
31749
31749
  ...description === undefined ? {} : { description },
31750
- ...values === undefined ? {} : { values }
31750
+ ...values === undefined ? {} : { values },
31751
+ shape: inner === undefined ? [] : shapeLines(inner, "")
31751
31752
  });
31752
31753
  }
31753
31754
  return fields;
@@ -31782,6 +31783,58 @@ function kindOf(field, node) {
31782
31783
  return "json";
31783
31784
  }
31784
31785
  }
31786
+ function withoutNull(node) {
31787
+ const members = (node.anyOf ?? [node]).filter((member) => member.type !== "null");
31788
+ return members.length === 1 ? members[0] : undefined;
31789
+ }
31790
+ function typeName(node) {
31791
+ if (node.anyOf !== undefined)
31792
+ return node.anyOf.map(typeName).join(" or ");
31793
+ if (node.enum !== undefined)
31794
+ return node.enum.map(String).join("|");
31795
+ switch (node.type) {
31796
+ case "string":
31797
+ return "text";
31798
+ case "integer":
31799
+ case "number":
31800
+ case "boolean":
31801
+ case "null":
31802
+ return node.type;
31803
+ case "object":
31804
+ return "object";
31805
+ case "array":
31806
+ return node.items === undefined ? "list" : `list of ${pluralTypeName(node.items)}`;
31807
+ default:
31808
+ return "any JSON";
31809
+ }
31810
+ }
31811
+ function pluralTypeName(node) {
31812
+ if (node.type === "object")
31813
+ return "objects";
31814
+ if (node.type === "integer")
31815
+ return "integers";
31816
+ if (node.type === "number")
31817
+ return "numbers";
31818
+ return typeName(node);
31819
+ }
31820
+ function shapeLines(node, indent) {
31821
+ const item = node.type === "array" ? node.items : undefined;
31822
+ const properties = (item ?? node).properties;
31823
+ if (properties === undefined)
31824
+ return [];
31825
+ const required = new Set((item ?? node).required ?? []);
31826
+ return [
31827
+ `${indent}${item === undefined ? "Its keys:" : "Each item's keys:"}`,
31828
+ ...Object.entries(properties).flatMap(([key, child]) => {
31829
+ const about = [required.has(key) ? "required" : undefined, typeName(child)].filter((part) => part !== undefined).join("; ");
31830
+ const inner = withoutNull(child);
31831
+ return [
31832
+ `${indent} ${key} (${about})${child.description === undefined ? "" : `: ${child.description}`}`,
31833
+ ...inner === undefined ? [] : shapeLines(inner, `${indent} `)
31834
+ ];
31835
+ })
31836
+ ];
31837
+ }
31785
31838
  function singular(field) {
31786
31839
  return field.endsWith("s") ? field.slice(0, -1) : field;
31787
31840
  }
@@ -31829,10 +31882,17 @@ function flagTable(tool, fields) {
31829
31882
  field,
31830
31883
  action: "json",
31831
31884
  value: "<json>",
31832
- text: `Every option as a JSON list of {label, description?}, in place of --${singular(name)}.`
31885
+ text: [`Every option as a JSON list, in place of --${singular(name)}.`, ...info.shape].join(`
31886
+ `)
31833
31887
  });
31834
31888
  } else if (kind === "json") {
31835
- add(`--${name}-json`, { field, action: "json", value: "<json>", text: about });
31889
+ add(`--${name}-json`, {
31890
+ field,
31891
+ action: "json",
31892
+ value: "<json>",
31893
+ text: [about, ...info.shape].filter((line) => line !== "").join(`
31894
+ `)
31895
+ });
31836
31896
  add(`--${name}-json-file`, {
31837
31897
  field,
31838
31898
  action: "json-file",
@@ -34416,7 +34476,8 @@ var ErrorWireSchema = object({
34416
34476
  });
34417
34477
  var EnvelopeResponseSchema = EnvelopeSchema.extend({
34418
34478
  recipient: string2().optional(),
34419
- holder: string2().optional()
34479
+ holder: string2().optional(),
34480
+ duplicate: boolean2().optional()
34420
34481
  });
34421
34482
  var ReplayWireSchema = object({
34422
34483
  stream: object({
@@ -34502,44 +34563,84 @@ class EnvoyApiError extends Error {
34502
34563
  this.code = parsed?.code;
34503
34564
  }
34504
34565
  }
34566
+ var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
34567
+
34568
+ class EnvoySendUnconfirmedError extends Error {
34569
+ targetSessionID;
34570
+ idempotencyKey;
34571
+ attempts;
34572
+ last;
34573
+ name = "EnvoySendUnconfirmedError";
34574
+ resendSafe;
34575
+ constructor(targetSessionID, idempotencyKey, attempts, last) {
34576
+ const got = last instanceof EnvoyApiError ? `the listener answered ${last.details.status} (${last.message})` : `the listener did not answer (${last instanceof Error ? last.message : String(last)})`;
34577
+ const tried = attempts === 1 ? "on its only attempt" : `on the last of ${attempts} attempts`;
34578
+ const resendSafe = mintedDedupeKey2.test(`agent.${targetSessionID.trim()}.${idempotencyKey}`);
34579
+ const resend = resendSafe ? `Sending it again with idempotency_key ${idempotencyKey} within ` + `${DELIVERY_DUPLICATE_WINDOW_MS / 3600000} hours is the safe resend: Envoy drops it as ` + "a repeat if the first copy arrived (a recipient that restarted in between can rarely " + "see it twice)." : `Envoy cannot recognise a resend under idempotency_key ${idempotencyKey} as a repeat ` + "(the key is not a lower-case UUID, or the session id holds a dot): ask the recipient " + "whether it arrived before sending it again.";
34580
+ super(`The send to ${targetSessionID} is not confirmed delivered: ${got} ${tried}. It may or may ` + `not have arrived. ${resend}`, { cause: last });
34581
+ this.targetSessionID = targetSessionID;
34582
+ this.idempotencyKey = idempotencyKey;
34583
+ this.attempts = attempts;
34584
+ this.last = last;
34585
+ this.resendSafe = resendSafe;
34586
+ }
34587
+ }
34505
34588
  function createEnvoyClient(config) {
34506
34589
  const baseUrl = normalizeEnvoyUrl(config.baseUrl);
34507
34590
  const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
34508
34591
  const apiToken = config.token;
34592
+ const attempts = config.retry === false ? 1 : 2;
34593
+ const attemptOnce = async (url, init, deadlineMs) => {
34594
+ const headers = new Headers(init.headers);
34595
+ if (apiToken)
34596
+ headers.set("Authorization", `Bearer ${apiToken}`);
34597
+ let response;
34598
+ try {
34599
+ response = await config.fetch(url, {
34600
+ ...init,
34601
+ headers,
34602
+ signal: AbortSignal.timeout(deadlineMs)
34603
+ });
34604
+ } catch (error) {
34605
+ return { unanswered: error };
34606
+ }
34607
+ try {
34608
+ return { response, body: await response.text() };
34609
+ } catch (error) {
34610
+ if (response.status >= 400 && response.status < 500) {
34611
+ return { response, body: `(its body did not arrive: ${String(error)})` };
34612
+ }
34613
+ return { unanswered: error };
34614
+ }
34615
+ };
34509
34616
  const request = async (path, init, options = {}) => {
34510
34617
  const url = `${baseUrl}${path}`;
34511
- const attempts = config.retry === false ? 1 : 2;
34512
34618
  const tries = options.retry === false ? 1 : attempts;
34513
34619
  for (let attempt = 0;attempt < tries; attempt += 1) {
34514
- let response;
34515
- try {
34516
- const headers = new Headers(init.headers);
34517
- if (apiToken)
34518
- headers.set("Authorization", `Bearer ${apiToken}`);
34519
- response = await config.fetch(url, {
34520
- ...init,
34521
- headers,
34522
- signal: AbortSignal.timeout(options.timeoutMs ?? timeoutMs)
34523
- });
34524
- } catch (error) {
34620
+ const outcome = await attemptOnce(url, init, options.timeoutMs ?? timeoutMs);
34621
+ if ("unanswered" in outcome) {
34622
+ options.onUnanswered?.();
34525
34623
  if (attempt + 1 < tries) {
34526
34624
  await waitForRetry();
34527
34625
  continue;
34528
34626
  }
34529
- throw error;
34627
+ throw outcome.unanswered;
34530
34628
  }
34531
- const responseBody = await response.text();
34629
+ const { response, body } = outcome;
34532
34630
  if (response.ok)
34533
- return responseBody;
34631
+ return body;
34534
34632
  const error = new EnvoyApiError({
34535
34633
  method: init.method ?? "GET",
34536
34634
  url,
34537
34635
  status: response.status,
34538
- responseBody
34636
+ responseBody: body
34539
34637
  });
34540
- if (response.status >= 500 && attempt + 1 < tries) {
34541
- await waitForRetry();
34542
- continue;
34638
+ if (response.status >= 500) {
34639
+ options.onUnanswered?.();
34640
+ if (attempt + 1 < tries) {
34641
+ await waitForRetry();
34642
+ continue;
34643
+ }
34543
34644
  }
34544
34645
  throw error;
34545
34646
  }
@@ -34575,18 +34676,33 @@ function createEnvoyClient(config) {
34575
34676
  getInterest: async (sessionID) => InterestWireSchema.parse(JSON.parse(await request(`/v1/interests/${sessionID}`, {}))),
34576
34677
  send: async (input) => {
34577
34678
  const idempotencyKey = input.idempotencyKey ?? crypto.randomUUID();
34578
- const response = EnvelopeResponseSchema.parse(JSON.parse(await post("/v1/messages/send", {
34579
- source: input.source ?? "agent",
34580
- ...sourceSession(input.sourceSessionID),
34581
- target_session: input.targetSessionID,
34582
- message: input.message,
34583
- idempotency_key: idempotencyKey,
34584
- ...messageMetadata(input)
34585
- })));
34679
+ let unanswered = false;
34680
+ let response;
34681
+ try {
34682
+ const answer = await post("/v1/messages/send", {
34683
+ source: input.source ?? "agent",
34684
+ ...sourceSession(input.sourceSessionID),
34685
+ target_session: input.targetSessionID,
34686
+ message: input.message,
34687
+ idempotency_key: idempotencyKey,
34688
+ ...messageMetadata(input)
34689
+ }, {
34690
+ onUnanswered: () => {
34691
+ unanswered = true;
34692
+ }
34693
+ });
34694
+ response = EnvelopeResponseSchema.parse(JSON.parse(answer));
34695
+ } catch (error) {
34696
+ if (error instanceof EnvoyApiError && error.details.status < 500 && !unanswered) {
34697
+ throw error;
34698
+ }
34699
+ throw new EnvoySendUnconfirmedError(input.targetSessionID, idempotencyKey, attempts, error);
34700
+ }
34586
34701
  return {
34587
34702
  envelope: response,
34588
34703
  recipient: response.recipient ?? input.targetSessionID,
34589
- confirmed: response.recipient !== undefined
34704
+ confirmed: response.recipient !== undefined,
34705
+ duplicate: response.duplicate === true
34590
34706
  };
34591
34707
  },
34592
34708
  publish: async (input) => {
@@ -34625,7 +34741,13 @@ function createEnvoyClient(config) {
34625
34741
  raw = await post("/v1/roles/set", body);
34626
34742
  } catch (error) {
34627
34743
  if (error instanceof EnvoyApiError && error.details.status === 409) {
34628
- const held = RoleHeldWireSchema.safeParse(JSON.parse(error.details.responseBody));
34744
+ let answer;
34745
+ try {
34746
+ answer = JSON.parse(error.details.responseBody);
34747
+ } catch {
34748
+ throw error;
34749
+ }
34750
+ const held = RoleHeldWireSchema.safeParse(answer);
34629
34751
  if (held.success)
34630
34752
  return { claimed: false, holder: held.data.holder };
34631
34753
  }
@@ -36961,16 +37083,11 @@ function artifactByReference(artifacts, artifactReference, owner, canonical) {
36961
37083
  const byId = artifacts.find((candidate) => candidate.id === artifactReference);
36962
37084
  if (byId !== undefined)
36963
37085
  return byId;
36964
- const byName = artifacts.filter((candidate) => candidate.name === artifactReference);
36965
- if (bySlug !== undefined) {
36966
- const named = byName.filter((candidate) => candidate.id !== bySlug.id && candidate.kind === "doc");
36967
- if (named.length > 0) {
36968
- throw new Error(documentReferenceProblem(artifactReference, [bySlug, ...named], owner, "id"));
36969
- }
37086
+ if (bySlug !== undefined)
36970
37087
  return bySlug;
36971
- }
37088
+ const byName = artifacts.filter((candidate) => candidate.name === artifactReference);
36972
37089
  if (byName.length > 1) {
36973
- throw new Error(documentReferenceProblem(artifactReference, byName, owner, "slug"));
37090
+ throw new Error(documentReferenceProblem(artifactReference, byName, owner, true));
36974
37091
  }
36975
37092
  const [artifact] = byName;
36976
37093
  if (artifact === undefined) {
@@ -37025,10 +37142,10 @@ async function documentTargets(client, resolution) {
37025
37142
  };
37026
37143
  }
37027
37144
  var documentHintLimit = 8;
37028
- function documentReferenceProblem(reference, documents, owner, use) {
37029
- const hints = documents.slice(0, documentHintLimit).map((document) => use === "id" ? `${document.id} (${document.slug}, ${document.name})` : `${document.slug} (${document.name})`);
37145
+ function documentReferenceProblem(reference, documents, owner, ambiguous = false) {
37146
+ const hints = documents.slice(0, documentHintLimit).map((document) => `${document.slug} (${document.name})`);
37030
37147
  const list = hints.length === 0 ? "none" : hints.join(", ");
37031
- return use === undefined ? `document "${reference}" not found by slug; this ${owner}'s documents: ${list}` : `"${reference}" names ${documents.length} documents on this ${owner}; use ${use === "id" ? "the id" : "a slug"}: ${list}`;
37148
+ return ambiguous ? `"${reference}" names ${documents.length} documents on this ${owner}; use a slug: ${list}` : `document "${reference}" not found by slug; this ${owner}'s documents: ${list}`;
37032
37149
  }
37033
37150
  async function liveBlocks(client, artifact) {
37034
37151
  const before = await client.docRead(artifact.id);
@@ -37626,10 +37743,11 @@ var envoyToolSpecs = [
37626
37743
  },
37627
37744
  {
37628
37745
  name: "envoy_send",
37629
- description: `Send an Envoy agent-to-agent message directly to another session by session ID. ${DELIVERY_CONTRACT}`,
37746
+ description: `Send an Envoy agent-to-agent message directly to another session by session ID. ${DELIVERY_CONTRACT} A send that is not confirmed delivered errs naming its idempotency_key; send the same message again with that idempotency_key within 72 hours, and Envoy drops it as a repeat if the first copy arrived.`,
37630
37747
  arguments: (schema) => ({
37631
37748
  session_id: schema.string().describe("Target session ID; find it with envoy_sessions or envoy_whoami."),
37632
- ...messageArguments(schema)
37749
+ ...messageArguments(schema),
37750
+ idempotency_key: schema.string().describe("Only to send again a message whose envoy_send was not confirmed delivered: the idempotency_key that error named. Omit it for a new message.").optional()
37633
37751
  }),
37634
37752
  operation: EnvoyToolOperation.send
37635
37753
  },
@@ -37679,6 +37797,9 @@ var envoyToolSpecs = [
37679
37797
  }
37680
37798
  ];
37681
37799
  function sendConfirmationText(result) {
37800
+ if (result.duplicate) {
37801
+ return `sent to ${result.recipient} once: an earlier attempt under the same idempotency_key was already stored, so this one stored no second copy`;
37802
+ }
37682
37803
  return `sent ${result.envelope.event_id} to ${result.recipient}${result.confirmed ? "" : " (recipient unconfirmed by listener)"}`;
37683
37804
  }
37684
37805
  function sessionsOnMachine(sessions, machine) {
@@ -37687,6 +37808,7 @@ function sessionsOnMachine(sessions, machine) {
37687
37808
  return sessions.filter((session) => session.host === machine || session.machine_id === machine);
37688
37809
  }
37689
37810
  var envoyToolSchemas = new Map;
37811
+ var SEND_IDEMPOTENCY_KEY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
37690
37812
  function parseEnvoyToolArguments(operation, parameters) {
37691
37813
  const spec = envoyToolSpecs.find((candidate) => candidate.operation === operation);
37692
37814
  if (spec === undefined)
@@ -37700,7 +37822,13 @@ function parseEnvoyToolArguments(operation, parameters) {
37700
37822
  if (!parsed.success) {
37701
37823
  throw new ToolInputError(spec.name, formatZodIssues(parsed.error.issues, schema, spec.name));
37702
37824
  }
37703
- return parsed.data;
37825
+ const { data } = parsed;
37826
+ if (typeof data === "object" && data !== null && "idempotency_key" in data && typeof data.idempotency_key === "string" && !SEND_IDEMPOTENCY_KEY.test(data.idempotency_key)) {
37827
+ throw new ToolInputError(spec.name, [
37828
+ `idempotency_key must be the key an unconfirmed send named, a lower-case UUID; got ${JSON.stringify(data.idempotency_key)}`
37829
+ ]);
37830
+ }
37831
+ return data;
37704
37832
  }
37705
37833
 
37706
37834
  // ../pi-shared/src/interface.ts
@@ -37993,7 +38121,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
37993
38121
 
37994
38122
  // package.json
37995
38123
  var name = "@sjawhar/pi-envoy";
37996
- var version2 = "15.0.1";
38124
+ var version2 = "15.0.3";
37997
38125
  var package_default = {
37998
38126
  name,
37999
38127
  version: version2,
@@ -45669,10 +45797,12 @@ Kept (they last while this session holds role ${registrationState.heldRole()}):
45669
45797
  return toolSuccess(JSON.stringify(inbox, null, 2), { count: inbox.length });
45670
45798
  case EnvoyToolOperation.send: {
45671
45799
  const targetSessionID = stringFor(parameters, "session_id");
45800
+ const idempotencyKey = parameters.idempotency_key;
45672
45801
  const result = await client.send({
45673
45802
  sourceSessionID: await replyAddress(context),
45674
45803
  targetSessionID,
45675
45804
  message: stringFor(parameters, "message"),
45805
+ ...typeof idempotencyKey === "string" ? { idempotencyKey } : {},
45676
45806
  ...toMessageMetadata(parameters)
45677
45807
  });
45678
45808
  return toolSuccess(sendConfirmationText(result), {
@@ -14,6 +14,7 @@ Envoy delivers external events and messages between sessions. Delivery is at-lea
14
14
  - Take the target id from the delivery's `reply_with`, or from `envoy_sessions` (filter by `machine`, `dir` or `title`). Never address a tmux pane or window: Envoy delivers only to a session id, and the session in a pane can change.
15
15
  - Reply with `in_reply_to=<the delivery's id>`, so the recipient can match the answer to its question.
16
16
  - Read the `recipient` in the send result, the session Envoy targeted: if it is not the one you meant, resend to the right id.
17
+ - When `envoy_send` says the send is not confirmed delivered, send the same message again with the `idempotency_key` the error names, within 72 hours: Envoy drops it as a repeat if the first copy arrived, and the result says when an earlier attempt was already stored. A resend without that key can deliver the message twice. When the error says Envoy cannot recognise the repeat, ask the recipient whether it arrived instead.
17
18
  - Put the URL or path of what you report in the message, because the recipient cannot find your files any other way.
18
19
  - Set `expects_reply="none"` on a message that needs no answer, and set `urgency` only when the work waits on the answer, so the recipient knows whether to answer and how soon. `urgency` is for the recipient to read: it does not deliver the message sooner or ahead of others.
19
20
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/pi-envoy",
3
- "version": "15.0.1",
3
+ "version": "15.0.3",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "omp": {