@bastani/atomic 0.9.85 → 0.9.86
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/CHANGELOG.md +40 -0
- package/dist/builtin/intercom/CHANGELOG.md +34 -0
- package/dist/builtin/intercom/README.md +10 -9
- package/dist/builtin/intercom/broker/away-asks.ts +272 -0
- package/dist/builtin/intercom/broker/broker.ts +171 -9
- package/dist/builtin/intercom/broker/client.ts +5 -3
- package/dist/builtin/intercom/broker/held-reply-targets.ts +5 -0
- package/dist/builtin/intercom/broker/multinode-router.ts +16 -7
- package/dist/builtin/intercom/broker/paths.ts +5 -0
- package/dist/builtin/intercom/broker/pending-question-index.ts +124 -0
- package/dist/builtin/intercom/broker/released-asker-replies.ts +39 -0
- package/dist/builtin/intercom/broker/send-handler.ts +44 -3
- package/dist/builtin/intercom/broker/terminal-questions.ts +2 -0
- package/dist/builtin/intercom/index.bundle.mjs +799 -177
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/intercom/retry-policy.ts +1 -1
- package/dist/builtin/intercom/skills/intercom/SKILL.md +29 -35
- package/dist/builtin/intercom/types.ts +7 -2
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +40 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/skills/subagent/SKILL.md +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +2765 -2719
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +24 -0
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/authoring.d.ts +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +371 -193
- package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +358 -181
- package/dist/builtin/workflows/src/index.js +356 -183
- package/dist/builtin/workflows/src/local-worker-entry.mjs +358 -181
- package/dist/builtin/workflows/src/shared/worktree-restore-outcome.d.ts +16 -0
- package/dist/builtin/workflows/src/workers/workspace-binding.d.ts +13 -2
- package/dist/core/agent-session-methods.d.ts +1 -0
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +2 -35
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +3 -1
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +12 -5
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-state.d.ts.map +1 -1
- package/dist/core/agent-session-state.js +14 -1
- package/dist/core/agent-session-state.js.map +1 -1
- package/dist/core/agent-session.d.ts +2 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +3 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/resume/index.d.ts +1 -1
- package/dist/core/resume/index.d.ts.map +1 -1
- package/dist/core/resume/index.js +1 -1
- package/dist/core/resume/index.js.map +1 -1
- package/dist/core/resume/path-mapping.d.ts +10 -0
- package/dist/core/resume/path-mapping.d.ts.map +1 -1
- package/dist/core/resume/path-mapping.js +20 -0
- package/dist/core/resume/path-mapping.js.map +1 -1
- package/dist/core/resume/session-resume.d.ts +5 -0
- package/dist/core/resume/session-resume.d.ts.map +1 -1
- package/dist/core/resume/session-resume.js +24 -9
- package/dist/core/resume/session-resume.js.map +1 -1
- package/dist/core/session-worktree-snapshots.d.ts +5 -8
- package/dist/core/session-worktree-snapshots.d.ts.map +1 -1
- package/dist/core/session-worktree-snapshots.js +34 -99
- package/dist/core/session-worktree-snapshots.js.map +1 -1
- package/dist/core/skill-catalog.d.ts +11 -0
- package/dist/core/skill-catalog.d.ts.map +1 -1
- package/dist/core/skill-catalog.js +31 -0
- package/dist/core/skill-catalog.js.map +1 -1
- package/dist/core/tasks/agent-adapter.d.ts +2 -0
- package/dist/core/tasks/agent-adapter.d.ts.map +1 -1
- package/dist/core/tasks/agent-adapter.js +5 -1
- package/dist/core/tasks/agent-adapter.js.map +1 -1
- package/dist/core/tasks/supervisor.d.ts +17 -0
- package/dist/core/tasks/supervisor.d.ts.map +1 -1
- package/dist/core/tasks/supervisor.js +12 -6
- package/dist/core/tasks/supervisor.js.map +1 -1
- package/dist/core/tasks/task-view-source.d.ts +10 -0
- package/dist/core/tasks/task-view-source.d.ts.map +1 -1
- package/dist/core/tasks/task-view-source.js +24 -1
- package/dist/core/tasks/task-view-source.js.map +1 -1
- package/dist/core/worktree-snapshot/best-restore.d.ts +45 -0
- package/dist/core/worktree-snapshot/best-restore.d.ts.map +1 -0
- package/dist/core/worktree-snapshot/best-restore.js +92 -0
- package/dist/core/worktree-snapshot/best-restore.js.map +1 -0
- package/dist/core/worktree-snapshot/git.d.ts +2 -2
- package/dist/core/worktree-snapshot/git.d.ts.map +1 -1
- package/dist/core/worktree-snapshot/git.js +2 -5
- package/dist/core/worktree-snapshot/git.js.map +1 -1
- package/dist/core/worktree-snapshot/index.d.ts +1 -0
- package/dist/core/worktree-snapshot/index.d.ts.map +1 -1
- package/dist/core/worktree-snapshot/index.js +1 -0
- package/dist/core/worktree-snapshot/index.js.map +1 -1
- package/dist/core/worktree-snapshot/restore.d.ts.map +1 -1
- package/dist/core/worktree-snapshot/restore.js +18 -2
- package/dist/core/worktree-snapshot/restore.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/chat-autocomplete.d.ts +7 -0
- package/dist/modes/interactive/chat-autocomplete.d.ts.map +1 -0
- package/dist/modes/interactive/chat-autocomplete.js +85 -0
- package/dist/modes/interactive/chat-autocomplete.js.map +1 -0
- package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-transcript-page.js +8 -0
- package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
- package/dist/modes/interactive/interactive-autocomplete.js +3 -79
- package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
- package/dist/modes/interactive/skill-command-autocomplete.d.ts +6 -0
- package/dist/modes/interactive/skill-command-autocomplete.d.ts.map +1 -1
- package/dist/modes/interactive/skill-command-autocomplete.js +18 -2
- package/dist/modes/interactive/skill-command-autocomplete.js.map +1 -1
- package/docs/background-tasks.md +1 -1
- package/docs/intercom/operations.md +4 -4
- package/docs/intercom/reference.md +39 -8
- package/docs/intercom.md +26 -9
- package/docs/skills.md +3 -1
- package/docs/subagents.md +2 -0
- package/docs/workflows/api-reference.md +3 -3
- package/docs/workflows/operations.md +2 -2
- package/docs/worktree-snapshots.md +10 -4
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
|
@@ -1137,6 +1137,55 @@ var init_intercom_utils = __esm(() => {
|
|
|
1137
1137
|
init_group();
|
|
1138
1138
|
});
|
|
1139
1139
|
|
|
1140
|
+
// dist/builtin/intercom/ask-wait.ts
|
|
1141
|
+
import { Type } from "typebox";
|
|
1142
|
+
function parseAskWait(value) {
|
|
1143
|
+
if (value === undefined)
|
|
1144
|
+
return;
|
|
1145
|
+
const invalid = new Error('Invalid ask wait: expected { kind: "background" } or { kind: "foreground", budgetMs? } with a finite non-negative budgetMs');
|
|
1146
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
1147
|
+
return invalid;
|
|
1148
|
+
const wait = value;
|
|
1149
|
+
if (Object.keys(wait).some((key) => key !== "kind" && (wait.kind !== "foreground" || key !== "budgetMs")))
|
|
1150
|
+
return invalid;
|
|
1151
|
+
if (wait.kind === "background")
|
|
1152
|
+
return { kind: "background" };
|
|
1153
|
+
if (wait.kind !== "foreground")
|
|
1154
|
+
return invalid;
|
|
1155
|
+
if (wait.budgetMs === undefined)
|
|
1156
|
+
return { kind: "foreground" };
|
|
1157
|
+
if (typeof wait.budgetMs !== "number" || !Number.isFinite(wait.budgetMs) || wait.budgetMs < 0)
|
|
1158
|
+
return invalid;
|
|
1159
|
+
return { kind: "foreground", budgetMs: wait.budgetMs };
|
|
1160
|
+
}
|
|
1161
|
+
var askWaitSchema, askIdSchema, ASK_DESCRIPTION = `\`ask\` never blocks you: it returns once the question is delivered, with an ask id and whether the recipient is
|
|
1162
|
+
idle or busy. A reply that comes within the wait (\`wait\` as in bash: omitted waits up to the automatic yield,
|
|
1163
|
+
\`{ kind: "foreground", budgetMs }\` up to the budget, \`{ kind: "background" }\` not at all) is returned inline;
|
|
1164
|
+
otherwise the ask stays pending with no expiry and its reply arrives later as a message starting
|
|
1165
|
+
"Reply to your ask <id> from <name>", which starts a turn when you are idle or arrives after your current tool call.
|
|
1166
|
+
A refusal or a recipient that ended arrives the same way as a failed-ask message. Do not re-ask while one is pending.`, ASK_USAGE = ` intercom({ action: "ask", to: "session-name", message: "..." }) → Ask; reply inline if quick, else later as a message
|
|
1167
|
+
intercom({ action: "ask", to: "session-name", message: "...", wait: { kind: "background" } }) → Ask without waiting
|
|
1168
|
+
intercom({ action: "cancel", askId: "..." }) → Cancel one of your pending asks`, ASK_PROMPT_SNIPPET = '`ask` does not block: a reply that misses the wait arrives later as a message ("Reply to your ask <id> from <name>").';
|
|
1169
|
+
var init_ask_wait = __esm(() => {
|
|
1170
|
+
askWaitSchema = Type.Unsafe({
|
|
1171
|
+
type: "object",
|
|
1172
|
+
properties: {
|
|
1173
|
+
kind: { type: "string", enum: ["background", "foreground"] },
|
|
1174
|
+
budgetMs: {
|
|
1175
|
+
type: "number",
|
|
1176
|
+
minimum: 0,
|
|
1177
|
+
description: "Foreground observation budget in milliseconds; only valid with foreground."
|
|
1178
|
+
}
|
|
1179
|
+
},
|
|
1180
|
+
required: ["kind"],
|
|
1181
|
+
additionalProperties: false,
|
|
1182
|
+
description: "For 'ask': how long to wait for the reply before yielding, as in bash. Omit for owner-configured automatic yield (default 10s). The ask stays pending after a yield and its reply arrives later as a message."
|
|
1183
|
+
});
|
|
1184
|
+
askIdSchema = Type.String({
|
|
1185
|
+
description: "For 'cancel': the id (or a unique prefix) of one of your pending asks, as 'ask' or 'pending' reported it"
|
|
1186
|
+
});
|
|
1187
|
+
});
|
|
1188
|
+
|
|
1140
1189
|
// dist/builtin/intercom/broker/client-message-validation.ts
|
|
1141
1190
|
function isAttachment(value) {
|
|
1142
1191
|
if (typeof value !== "object" || value === null)
|
|
@@ -3158,7 +3207,7 @@ var init_client = __esm(() => {
|
|
|
3158
3207
|
throw new Error(`Unknown broker message type: ${brokerMessage.type}`);
|
|
3159
3208
|
}
|
|
3160
3209
|
}
|
|
3161
|
-
async disconnect() {
|
|
3210
|
+
async disconnect(options = {}) {
|
|
3162
3211
|
if (this.connectAttempt !== undefined && this._sessionId === null) {
|
|
3163
3212
|
this.connectAttempt.abort();
|
|
3164
3213
|
return;
|
|
@@ -3192,7 +3241,7 @@ var init_client = __esm(() => {
|
|
|
3192
3241
|
socket.once("close", onClose);
|
|
3193
3242
|
socket.once("error", onError);
|
|
3194
3243
|
try {
|
|
3195
|
-
writeMessage(socket, { type: "unregister" });
|
|
3244
|
+
writeMessage(socket, { type: "unregister", ...options.resumable === true ? { resumable: true } : {} });
|
|
3196
3245
|
socket.end();
|
|
3197
3246
|
} catch {
|
|
3198
3247
|
socket.destroy();
|
|
@@ -3452,7 +3501,7 @@ var init_client = __esm(() => {
|
|
|
3452
3501
|
}
|
|
3453
3502
|
return this.restoringRecipientRequest({ type: "acknowledge_released_child_wake", childName });
|
|
3454
3503
|
}
|
|
3455
|
-
acknowledgeReleasedChildReply(reply, accepted) {
|
|
3504
|
+
acknowledgeReleasedChildReply(reply, accepted, deliverToChild = false) {
|
|
3456
3505
|
if (!this.socket || this.socket.destroyed)
|
|
3457
3506
|
return false;
|
|
3458
3507
|
this.requireBrokerProtocol("released_child_reply_ack");
|
|
@@ -3460,7 +3509,8 @@ var init_client = __esm(() => {
|
|
|
3460
3509
|
type: "released_child_reply_ack",
|
|
3461
3510
|
messageId: reply.message.id,
|
|
3462
3511
|
handoffId: reply.handoffId,
|
|
3463
|
-
accepted
|
|
3512
|
+
accepted,
|
|
3513
|
+
...deliverToChild ? { deliverToChild: true } : {}
|
|
3464
3514
|
});
|
|
3465
3515
|
return true;
|
|
3466
3516
|
}
|
|
@@ -4563,12 +4613,14 @@ class InlineMessageComponent {
|
|
|
4563
4613
|
theme;
|
|
4564
4614
|
replyCommand;
|
|
4565
4615
|
bodyText;
|
|
4566
|
-
|
|
4616
|
+
heading;
|
|
4617
|
+
constructor(from, message, theme, replyCommand, bodyText, heading) {
|
|
4567
4618
|
this.from = from;
|
|
4568
4619
|
this.message = message;
|
|
4569
4620
|
this.theme = theme;
|
|
4570
4621
|
this.replyCommand = replyCommand;
|
|
4571
4622
|
this.bodyText = bodyText;
|
|
4623
|
+
this.heading = heading;
|
|
4572
4624
|
}
|
|
4573
4625
|
invalidate() {}
|
|
4574
4626
|
render(width) {
|
|
@@ -4579,7 +4631,7 @@ class InlineMessageComponent {
|
|
|
4579
4631
|
}
|
|
4580
4632
|
const bodyWidth = Math.max(1, width - 2);
|
|
4581
4633
|
const senderName = this.from.name || this.from.id;
|
|
4582
|
-
const header = ` \uD83D\uDCE8 From: ${senderName} (${this.from.cwd}) `;
|
|
4634
|
+
const header = this.heading === undefined ? ` \uD83D\uDCE8 From: ${senderName} (${this.from.cwd}) ` : ` \uD83D\uDCE8 ${this.heading} `;
|
|
4583
4635
|
const headerText = truncateToWidth(header, bodyWidth, "…");
|
|
4584
4636
|
const headerPadding = Math.max(0, bodyWidth - visibleWidth(headerText));
|
|
4585
4637
|
lines.push(this.theme.fg("accent", `╭${headerText}${borderChar.repeat(headerPadding)}╮`));
|
|
@@ -4643,6 +4695,9 @@ class ReplyWaiterRegistry {
|
|
|
4643
4695
|
if (waiter?.from === previousSessionId)
|
|
4644
4696
|
waiter.from = sessionId;
|
|
4645
4697
|
}
|
|
4698
|
+
cancel(replyTo, error) {
|
|
4699
|
+
this.waiters.get(replyTo)?.reject(error);
|
|
4700
|
+
}
|
|
4646
4701
|
get limit() {
|
|
4647
4702
|
return this.maxPending;
|
|
4648
4703
|
}
|
|
@@ -4661,19 +4716,19 @@ class ReplyWaiterRegistry {
|
|
|
4661
4716
|
}
|
|
4662
4717
|
return released;
|
|
4663
4718
|
}
|
|
4664
|
-
begin(from, replyTo, signal) {
|
|
4719
|
+
begin(from, replyTo, signal, timeoutMs = this.timeoutMs) {
|
|
4665
4720
|
if (signal?.aborted)
|
|
4666
4721
|
return { ok: false, reason: "cancelled" };
|
|
4667
4722
|
if (this.waiters.size >= this.maxPending) {
|
|
4668
4723
|
return { ok: false, reason: "busy", limit: this.maxPending };
|
|
4669
4724
|
}
|
|
4670
|
-
const deadline = Date.now() +
|
|
4725
|
+
const deadline = timeoutMs === null ? Number.MAX_SAFE_INTEGER : Date.now() + timeoutMs;
|
|
4671
4726
|
let record;
|
|
4672
4727
|
const promise = new Promise((resolve, reject) => {
|
|
4673
4728
|
let settled = false;
|
|
4674
|
-
const timeout = setTimeout(() => {
|
|
4675
|
-
record.reject(new Error(`No reply from "${from}" within ${Math.round(
|
|
4676
|
-
},
|
|
4729
|
+
const timeout = timeoutMs === null ? undefined : setTimeout(() => {
|
|
4730
|
+
record.reject(new Error(`No reply from "${from}" within ${Math.round(timeoutMs / 60000)} minutes`));
|
|
4731
|
+
}, timeoutMs);
|
|
4677
4732
|
const onAbort = () => record.reject(new Error("Cancelled"));
|
|
4678
4733
|
const cleanup = () => {
|
|
4679
4734
|
settled = true;
|
|
@@ -4890,14 +4945,10 @@ var init_session_target = __esm(() => {
|
|
|
4890
4945
|
|
|
4891
4946
|
// dist/builtin/intercom/reply-tracker.ts
|
|
4892
4947
|
class ReplyTracker {
|
|
4893
|
-
askTimeoutMs;
|
|
4894
4948
|
pendingAsks = new Map;
|
|
4895
4949
|
pendingTurnContexts = [];
|
|
4896
4950
|
currentTurnContext = null;
|
|
4897
4951
|
turnContextAdmitted = false;
|
|
4898
|
-
constructor(askTimeoutMs = ASK_REPLY_TIMEOUT_MS) {
|
|
4899
|
-
this.askTimeoutMs = askTimeoutMs;
|
|
4900
|
-
}
|
|
4901
4952
|
recordIncomingMessage(from, message, receivedAt = Date.now()) {
|
|
4902
4953
|
const context = { from, message, receivedAt };
|
|
4903
4954
|
if (message.expectsReply) {
|
|
@@ -4918,8 +4969,7 @@ class ReplyTracker {
|
|
|
4918
4969
|
if (this.currentTurnContext === context)
|
|
4919
4970
|
this.currentTurnContext = null;
|
|
4920
4971
|
}
|
|
4921
|
-
beginTurn(
|
|
4922
|
-
this.pruneExpired(now);
|
|
4972
|
+
beginTurn() {
|
|
4923
4973
|
this.turnContextAdmitted = false;
|
|
4924
4974
|
}
|
|
4925
4975
|
admitTurnMessage(messageId) {
|
|
@@ -4947,8 +4997,7 @@ class ReplyTracker {
|
|
|
4947
4997
|
this.pendingTurnContexts.length = 0;
|
|
4948
4998
|
this.currentTurnContext = null;
|
|
4949
4999
|
}
|
|
4950
|
-
resolveReplyTarget(options
|
|
4951
|
-
this.pruneExpired(now);
|
|
5000
|
+
resolveReplyTarget(options) {
|
|
4952
5001
|
if (options.replyTo !== undefined) {
|
|
4953
5002
|
const contexts = new Map(this.pendingAsks);
|
|
4954
5003
|
if (this.currentTurnContext && !this.currentTurnContext.message.expectsReply) {
|
|
@@ -5008,23 +5057,212 @@ class ReplyTracker {
|
|
|
5008
5057
|
this.currentTurnContext = null;
|
|
5009
5058
|
}
|
|
5010
5059
|
}
|
|
5011
|
-
listPending(
|
|
5012
|
-
this.pruneExpired(now);
|
|
5060
|
+
listPending() {
|
|
5013
5061
|
return Array.from(this.pendingAsks.values()).sort((a, b) => a.receivedAt - b.receivedAt);
|
|
5014
5062
|
}
|
|
5015
|
-
|
|
5016
|
-
|
|
5017
|
-
|
|
5018
|
-
|
|
5019
|
-
|
|
5063
|
+
}
|
|
5064
|
+
function restorePendingInboundAsks(tracker, entries, sessionId) {
|
|
5065
|
+
const asks = new Map;
|
|
5066
|
+
const answered = new Set;
|
|
5067
|
+
let registered = false;
|
|
5068
|
+
for (const entry of entries) {
|
|
5069
|
+
if (!registered) {
|
|
5070
|
+
registered = entry.type === "custom" && entry.customType === INTERCOM_SESSION_IDENTITY_ENTRY && entry.data?.sessionId === sessionId;
|
|
5071
|
+
continue;
|
|
5020
5072
|
}
|
|
5073
|
+
if (entry.type === "custom_message" && entry.customType === "intercom_message") {
|
|
5074
|
+
const details = entry.details;
|
|
5075
|
+
if (!isSessionInfo(details?.from) || !isMessage(details.message) || details.message.expectsReply !== true)
|
|
5076
|
+
continue;
|
|
5077
|
+
if (details.historyOnly === true)
|
|
5078
|
+
continue;
|
|
5079
|
+
asks.set(details.message.id, { from: details.from, message: details.message, receivedAt: Date.parse(entry.timestamp) || Date.now() });
|
|
5080
|
+
} else if (entry.type === "custom" && entry.customType === "intercom_sent") {
|
|
5081
|
+
const replyTo = entry.data?.message?.replyTo;
|
|
5082
|
+
if (typeof replyTo === "string")
|
|
5083
|
+
answered.add(replyTo);
|
|
5084
|
+
}
|
|
5085
|
+
}
|
|
5086
|
+
for (const [id, context] of asks) {
|
|
5087
|
+
if (!answered.has(id))
|
|
5088
|
+
tracker.recordIncomingMessage(context.from, context.message, context.receivedAt);
|
|
5021
5089
|
}
|
|
5022
5090
|
}
|
|
5023
5091
|
var init_reply_tracker = __esm(() => {
|
|
5024
|
-
init_retry_policy();
|
|
5025
5092
|
init_session_target();
|
|
5026
5093
|
});
|
|
5027
5094
|
|
|
5095
|
+
// dist/builtin/intercom/outbound-asks.ts
|
|
5096
|
+
function isOutboundAsk(value) {
|
|
5097
|
+
if (typeof value !== "object" || value === null)
|
|
5098
|
+
return false;
|
|
5099
|
+
const ask = value;
|
|
5100
|
+
return typeof ask.askId === "string" && typeof ask.sessionId === "string" && typeof ask.to === "string" && typeof ask.recipientId === "string" && typeof ask.question === "string" && typeof ask.askedAt === "number";
|
|
5101
|
+
}
|
|
5102
|
+
function isSettledState(value) {
|
|
5103
|
+
return value === "answered" || value === "cancelled" || value === "failed";
|
|
5104
|
+
}
|
|
5105
|
+
|
|
5106
|
+
class OutboundAsks {
|
|
5107
|
+
options;
|
|
5108
|
+
opened = new Map;
|
|
5109
|
+
settled = new Map;
|
|
5110
|
+
constructor(options) {
|
|
5111
|
+
this.options = options;
|
|
5112
|
+
}
|
|
5113
|
+
open(ask) {
|
|
5114
|
+
const opened = { ...ask, sessionId: this.options.sessionId() ?? "", askedAt: this.options.now?.() ?? Date.now() };
|
|
5115
|
+
this.opened.set(ask.askId, opened);
|
|
5116
|
+
return opened;
|
|
5117
|
+
}
|
|
5118
|
+
forget(askId) {
|
|
5119
|
+
this.opened.delete(askId);
|
|
5120
|
+
}
|
|
5121
|
+
async persist(askId) {
|
|
5122
|
+
const ask = this.opened.get(askId);
|
|
5123
|
+
if (ask === undefined)
|
|
5124
|
+
return;
|
|
5125
|
+
await this.options.append(OUTBOUND_ASK_ENTRY, ask);
|
|
5126
|
+
}
|
|
5127
|
+
find(askId) {
|
|
5128
|
+
const records = this.records();
|
|
5129
|
+
return records.get(askId);
|
|
5130
|
+
}
|
|
5131
|
+
answeredBy(from, message) {
|
|
5132
|
+
if (message.replyTo === undefined || message.expectsReply === true)
|
|
5133
|
+
return;
|
|
5134
|
+
const record = this.find(message.replyTo);
|
|
5135
|
+
return record !== undefined && answeredByRecipient(record.ask, from) ? record : undefined;
|
|
5136
|
+
}
|
|
5137
|
+
pending() {
|
|
5138
|
+
return [...this.records().values()].filter((record) => record.state === "pending").map((record) => record.ask).sort((left, right) => left.askedAt - right.askedAt);
|
|
5139
|
+
}
|
|
5140
|
+
async settle(askId, state) {
|
|
5141
|
+
const record = this.find(askId);
|
|
5142
|
+
if (record === undefined || record.state !== "pending")
|
|
5143
|
+
return false;
|
|
5144
|
+
this.settled.set(askId, state);
|
|
5145
|
+
try {
|
|
5146
|
+
await this.options.append(OUTBOUND_ASK_SETTLED_ENTRY, { askId, state });
|
|
5147
|
+
} catch {}
|
|
5148
|
+
return true;
|
|
5149
|
+
}
|
|
5150
|
+
records() {
|
|
5151
|
+
const asks = new Map;
|
|
5152
|
+
const states = new Map;
|
|
5153
|
+
let entries = [];
|
|
5154
|
+
try {
|
|
5155
|
+
entries = [...this.options.entries()];
|
|
5156
|
+
} catch {
|
|
5157
|
+
entries = [];
|
|
5158
|
+
}
|
|
5159
|
+
const owner = this.options.sessionId();
|
|
5160
|
+
for (const entry of entries) {
|
|
5161
|
+
if (entry.type !== "custom")
|
|
5162
|
+
continue;
|
|
5163
|
+
if (entry.customType === OUTBOUND_ASK_ENTRY && isOutboundAsk(entry.data) && entry.data.sessionId === owner)
|
|
5164
|
+
asks.set(entry.data.askId, entry.data);
|
|
5165
|
+
if (entry.customType === OUTBOUND_ASK_SETTLED_ENTRY) {
|
|
5166
|
+
const data = entry.data;
|
|
5167
|
+
if (typeof data?.askId === "string" && isSettledState(data.state) && !states.has(data.askId)) {
|
|
5168
|
+
states.set(data.askId, data.state);
|
|
5169
|
+
}
|
|
5170
|
+
}
|
|
5171
|
+
}
|
|
5172
|
+
for (const [askId, ask] of this.opened)
|
|
5173
|
+
if (!asks.has(askId))
|
|
5174
|
+
asks.set(askId, ask);
|
|
5175
|
+
for (const [askId, state] of this.settled)
|
|
5176
|
+
if (!states.has(askId))
|
|
5177
|
+
states.set(askId, state);
|
|
5178
|
+
for (const { from, message } of savedArrivals(entries)) {
|
|
5179
|
+
if (message.replyTo === undefined || message.expectsReply === true || states.has(message.replyTo))
|
|
5180
|
+
continue;
|
|
5181
|
+
const ask = asks.get(message.replyTo);
|
|
5182
|
+
if (ask === undefined || !answeredByRecipient(ask, from))
|
|
5183
|
+
continue;
|
|
5184
|
+
states.set(ask.askId, message.replyError === undefined ? "answered" : "failed");
|
|
5185
|
+
}
|
|
5186
|
+
const records = new Map;
|
|
5187
|
+
for (const [askId, ask] of asks)
|
|
5188
|
+
records.set(askId, { ask, state: states.get(askId) ?? "pending" });
|
|
5189
|
+
return records;
|
|
5190
|
+
}
|
|
5191
|
+
}
|
|
5192
|
+
function answeredByRecipient(ask, from) {
|
|
5193
|
+
const named = from.name !== undefined && from.name.toLowerCase() === ask.to.trim().toLowerCase();
|
|
5194
|
+
return from.id === ask.recipientId || named;
|
|
5195
|
+
}
|
|
5196
|
+
function* savedArrivals(entries) {
|
|
5197
|
+
for (const entry of entries) {
|
|
5198
|
+
const data = entry.type === "custom" && entry.customType === INTERCOM_INBOX_ENTRY ? entry.data : entry.type === "custom_message" && entry.customType === "intercom_message" ? entry.details : undefined;
|
|
5199
|
+
if (isSessionInfo(data?.from) && isMessage(data.message))
|
|
5200
|
+
yield { from: data.from, message: data.message };
|
|
5201
|
+
}
|
|
5202
|
+
}
|
|
5203
|
+
function quote(text) {
|
|
5204
|
+
return text.split(`
|
|
5205
|
+
`).map((line) => `> ${line}`).join(`
|
|
5206
|
+
`);
|
|
5207
|
+
}
|
|
5208
|
+
function frameOutboundAskReply(entry, record) {
|
|
5209
|
+
const sender = entry.from.name || entry.from.id;
|
|
5210
|
+
const { ask } = record;
|
|
5211
|
+
if (entry.message.replyError !== undefined) {
|
|
5212
|
+
return {
|
|
5213
|
+
...entry,
|
|
5214
|
+
replyCommand: undefined,
|
|
5215
|
+
heading: `Your ask ${ask.askId} to ${sender} failed`,
|
|
5216
|
+
bodyText: `Question:
|
|
5217
|
+
${quote(ask.question)}
|
|
5218
|
+
|
|
5219
|
+
Reason: ${entry.message.replyError}`
|
|
5220
|
+
};
|
|
5221
|
+
}
|
|
5222
|
+
const late = record.state === "cancelled" ? " (late: you cancelled this ask)" : "";
|
|
5223
|
+
return {
|
|
5224
|
+
...entry,
|
|
5225
|
+
heading: `Reply to your ask ${ask.askId} from ${sender}${late}`,
|
|
5226
|
+
bodyText: `Question:
|
|
5227
|
+
${quote(ask.question)}
|
|
5228
|
+
|
|
5229
|
+
Reply:
|
|
5230
|
+
${entry.bodyText}`
|
|
5231
|
+
};
|
|
5232
|
+
}
|
|
5233
|
+
function recipientClosedAskEntry(ask, peer, now = Date.now()) {
|
|
5234
|
+
const reason = `Session "${peer.name ?? peer.sessionId}" ended before replying`;
|
|
5235
|
+
const from = {
|
|
5236
|
+
id: peer.sessionId,
|
|
5237
|
+
...peer.name === undefined ? {} : { name: peer.name },
|
|
5238
|
+
cwd: "",
|
|
5239
|
+
model: "",
|
|
5240
|
+
pid: 0,
|
|
5241
|
+
startedAt: 0,
|
|
5242
|
+
lastActivity: now
|
|
5243
|
+
};
|
|
5244
|
+
const message = {
|
|
5245
|
+
id: `${ask.askId}:recipient-closed`,
|
|
5246
|
+
timestamp: now,
|
|
5247
|
+
replyTo: ask.askId,
|
|
5248
|
+
replyError: reason,
|
|
5249
|
+
content: { text: reason }
|
|
5250
|
+
};
|
|
5251
|
+
return {
|
|
5252
|
+
from,
|
|
5253
|
+
message,
|
|
5254
|
+
heading: `Your ask ${ask.askId} to ${peer.name ?? peer.sessionId} failed`,
|
|
5255
|
+
bodyText: `Question:
|
|
5256
|
+
${quote(ask.question)}
|
|
5257
|
+
|
|
5258
|
+
Reason: ${reason}`
|
|
5259
|
+
};
|
|
5260
|
+
}
|
|
5261
|
+
var OUTBOUND_ASK_ENTRY = "intercom_ask", OUTBOUND_ASK_SETTLED_ENTRY = "intercom_ask_settled";
|
|
5262
|
+
var init_outbound_asks = __esm(() => {
|
|
5263
|
+
init_durable_inbox();
|
|
5264
|
+
});
|
|
5265
|
+
|
|
5028
5266
|
// dist/builtin/intercom/released-reply-wait.ts
|
|
5029
5267
|
import { markToolCallReadyForDetachment, toolCallNeedsDetachmentHandoff } from "@bastani/atomic";
|
|
5030
5268
|
function replyWaitMayDetach(connected, routing) {
|
|
@@ -5105,7 +5343,7 @@ var init_parent_ask_handoff = __esm(() => {
|
|
|
5105
5343
|
|
|
5106
5344
|
// dist/builtin/intercom/contact-supervisor-tool.ts
|
|
5107
5345
|
import { randomUUID as randomUUID5 } from "crypto";
|
|
5108
|
-
import { Type } from "typebox";
|
|
5346
|
+
import { Type as Type2 } from "typebox";
|
|
5109
5347
|
import { Text as Text2 } from "@earendil-works/pi-tui";
|
|
5110
5348
|
function registerContactSupervisorTool(pi, deps) {
|
|
5111
5349
|
const { childOrchestratorMetadata, ensureConnected, syncPresenceIdentity, resolveSessionTarget, beginReplyWait } = deps;
|
|
@@ -5127,23 +5365,23 @@ function registerContactSupervisorTool(pi, deps) {
|
|
|
5127
5365
|
"Use contact_supervisor with reason='progress_update' only for meaningful progress or unexpected discoveries that change the plan.",
|
|
5128
5366
|
"Do not use contact_supervisor for routine completion handoffs; return the final subagent result normally."
|
|
5129
5367
|
],
|
|
5130
|
-
parameters:
|
|
5131
|
-
reason:
|
|
5368
|
+
parameters: Type2.Object({
|
|
5369
|
+
reason: Type2.String({
|
|
5132
5370
|
enum: ["need_decision", "progress_update", "interview_request"],
|
|
5133
5371
|
description: "Contact reason: 'need_decision' and 'interview_request' yield a live foreground child for a fresh follow-up; 'progress_update' sends a non-blocking update"
|
|
5134
5372
|
}),
|
|
5135
|
-
message:
|
|
5373
|
+
message: Type2.Optional(Type2.String({
|
|
5136
5374
|
description: "Decision request, optional interview note, or meaningful progress update for the supervisor"
|
|
5137
5375
|
})),
|
|
5138
|
-
interview:
|
|
5139
|
-
title:
|
|
5140
|
-
description:
|
|
5141
|
-
questions:
|
|
5142
|
-
id:
|
|
5143
|
-
type:
|
|
5144
|
-
question:
|
|
5145
|
-
options:
|
|
5146
|
-
context:
|
|
5376
|
+
interview: Type2.Optional(Type2.Object({
|
|
5377
|
+
title: Type2.Optional(Type2.String()),
|
|
5378
|
+
description: Type2.Optional(Type2.String()),
|
|
5379
|
+
questions: Type2.Array(Type2.Object({
|
|
5380
|
+
id: Type2.String(),
|
|
5381
|
+
type: Type2.String({ description: "Question type: single, multi, text, image, or info" }),
|
|
5382
|
+
question: Type2.String(),
|
|
5383
|
+
options: Type2.Optional(Type2.Array(Type2.Unknown())),
|
|
5384
|
+
context: Type2.Optional(Type2.String())
|
|
5147
5385
|
}))
|
|
5148
5386
|
}, { description: "Structured interview request for reason='interview_request'" }))
|
|
5149
5387
|
}),
|
|
@@ -5407,6 +5645,34 @@ var init_contact_supervisor_tool = __esm(() => {
|
|
|
5407
5645
|
init_intercom_utils();
|
|
5408
5646
|
});
|
|
5409
5647
|
|
|
5648
|
+
// dist/builtin/intercom/broker/held-reply-targets.ts
|
|
5649
|
+
var OFFLINE_SESSION_TARGET = "offline session", HELD_FOR_AWAY_ASKER_TARGET = "held for asker";
|
|
5650
|
+
|
|
5651
|
+
// dist/builtin/intercom/peer-disconnect-routing.ts
|
|
5652
|
+
function matches(waiter, notice) {
|
|
5653
|
+
const peerTarget = notice.peerName || notice.peerSessionId;
|
|
5654
|
+
const peerMatches = peerTarget.toLowerCase() === waiter.from.toLowerCase() || notice.peerSessionId === waiter.from;
|
|
5655
|
+
return peerMatches && notice.replyTo === waiter.replyTo;
|
|
5656
|
+
}
|
|
5657
|
+
function routePeerDisconnect(waiters, notice) {
|
|
5658
|
+
if (!waiters)
|
|
5659
|
+
return false;
|
|
5660
|
+
const candidates = Symbol.iterator in Object(waiters) ? waiters : [waiters];
|
|
5661
|
+
for (const waiter of candidates) {
|
|
5662
|
+
if (!matches(waiter, notice))
|
|
5663
|
+
continue;
|
|
5664
|
+
waiter.reject(new PeerDisconnectedError(`Session "${notice.peerName ?? notice.peerSessionId}" disconnected before replying`));
|
|
5665
|
+
return true;
|
|
5666
|
+
}
|
|
5667
|
+
return false;
|
|
5668
|
+
}
|
|
5669
|
+
var PeerDisconnectedError;
|
|
5670
|
+
var init_peer_disconnect_routing = __esm(() => {
|
|
5671
|
+
PeerDisconnectedError = class PeerDisconnectedError extends Error {
|
|
5672
|
+
name = "PeerDisconnectedError";
|
|
5673
|
+
};
|
|
5674
|
+
});
|
|
5675
|
+
|
|
5410
5676
|
// dist/builtin/intercom/project-group.ts
|
|
5411
5677
|
import { spawnSync } from "node:child_process";
|
|
5412
5678
|
import { existsSync as existsSync3 } from "node:fs";
|
|
@@ -5852,9 +6118,99 @@ var init_tool_retry = __esm(() => {
|
|
|
5852
6118
|
init_retry_policy();
|
|
5853
6119
|
});
|
|
5854
6120
|
|
|
6121
|
+
// dist/builtin/intercom/send-pattern-targets.ts
|
|
6122
|
+
function parseSendPatternTarget(target) {
|
|
6123
|
+
const trimmed = target.trim();
|
|
6124
|
+
if (trimmed.startsWith(SUBAGENTS_TARGET_PREFIX)) {
|
|
6125
|
+
const selector = trimmed.slice(SUBAGENTS_TARGET_PREFIX.length);
|
|
6126
|
+
if (selector === "*")
|
|
6127
|
+
return { kind: "subagents" };
|
|
6128
|
+
const runId = selector.endsWith("/*") ? selector.slice(0, -2) : "";
|
|
6129
|
+
if (runId.length > 0 && !runId.includes("/") && !runId.includes("*"))
|
|
6130
|
+
return { kind: "subagents", runId };
|
|
6131
|
+
return {
|
|
6132
|
+
kind: "invalid",
|
|
6133
|
+
reason: `Invalid subagents target "${trimmed}": use \`subagents:*\` for every subagent this session launched, or \`subagents:<runId>/*\` for those of one run.`
|
|
6134
|
+
};
|
|
6135
|
+
}
|
|
6136
|
+
if (trimmed.startsWith(WORKFLOW_TARGET_PREFIX2) || !trimmed.includes("*"))
|
|
6137
|
+
return;
|
|
6138
|
+
return { kind: "sessions", pattern: trimmed };
|
|
6139
|
+
}
|
|
6140
|
+
function globExpression(pattern) {
|
|
6141
|
+
const source = pattern.split("*").map((literal) => literal.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
6142
|
+
return new RegExp(`^${source}$`, "i");
|
|
6143
|
+
}
|
|
6144
|
+
function sessionPatternName(session) {
|
|
6145
|
+
return session.name?.trim() || session.id;
|
|
6146
|
+
}
|
|
6147
|
+
function matchSessionPattern(sessions, pattern, selfId) {
|
|
6148
|
+
const expression = globExpression(pattern);
|
|
6149
|
+
return sessions.filter((session) => session.id !== selfId && expression.test(sessionPatternName(session)));
|
|
6150
|
+
}
|
|
6151
|
+
function editDistance(left, right) {
|
|
6152
|
+
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
6153
|
+
for (let row = 1;row <= left.length; row++) {
|
|
6154
|
+
const current = [row];
|
|
6155
|
+
for (let column = 1;column <= right.length; column++) {
|
|
6156
|
+
const substitution = previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1);
|
|
6157
|
+
current[column] = Math.min(previous[column] + 1, current[column - 1] + 1, substitution);
|
|
6158
|
+
}
|
|
6159
|
+
previous = current;
|
|
6160
|
+
}
|
|
6161
|
+
return previous[right.length];
|
|
6162
|
+
}
|
|
6163
|
+
function windowDistance(literal, name) {
|
|
6164
|
+
let best = editDistance(literal, name);
|
|
6165
|
+
for (let start = 0;start + literal.length <= name.length; start++) {
|
|
6166
|
+
best = Math.min(best, editDistance(literal, name.slice(start, start + literal.length)));
|
|
6167
|
+
}
|
|
6168
|
+
return best;
|
|
6169
|
+
}
|
|
6170
|
+
function closeSessionNames(sessions, pattern, selfId) {
|
|
6171
|
+
const literal = pattern.replaceAll("*", "").toLowerCase();
|
|
6172
|
+
return sessions.filter((session) => session.id !== selfId).map((session) => sessionPatternName(session)).map((name) => ({ name, distance: windowDistance(literal, name.toLowerCase()) })).sort((left, right) => left.distance - right.distance || left.name.localeCompare(right.name)).slice(0, CLOSE_NAME_LIMIT).map(({ name }) => name);
|
|
6173
|
+
}
|
|
6174
|
+
async function listIntercomChildren(events, ownerSessionId, runId) {
|
|
6175
|
+
if (events === undefined)
|
|
6176
|
+
return [];
|
|
6177
|
+
const request = { ownerSessionId, ...runId === undefined ? {} : { runId } };
|
|
6178
|
+
events.emit(SUBAGENT_LIST_INTERCOM_CHILDREN_EVENT, request);
|
|
6179
|
+
return await request.completion ?? [];
|
|
6180
|
+
}
|
|
6181
|
+
function patternSendResult(target, recipients) {
|
|
6182
|
+
const reached = recipients.filter((recipient) => recipient.outcome === "delivered" || recipient.outcome === "queued");
|
|
6183
|
+
const lines = recipients.map((recipient) => {
|
|
6184
|
+
if (recipient.outcome === "delivered")
|
|
6185
|
+
return `- ${recipient.label}: delivered`;
|
|
6186
|
+
if (recipient.outcome === "queued")
|
|
6187
|
+
return `- ${recipient.label}: queued`;
|
|
6188
|
+
const state = recipient.outcome === "unknown" ? "outcome unknown" : "not delivered";
|
|
6189
|
+
return `- ${recipient.label}: ${state}: ${recipient.reason ?? "no reason given"}`;
|
|
6190
|
+
});
|
|
6191
|
+
const count = `${reached.length} of ${recipients.length} recipient${recipients.length === 1 ? "" : "s"}`;
|
|
6192
|
+
return {
|
|
6193
|
+
content: [{ type: "text", text: `Message to \`${target}\` reached ${count}:
|
|
6194
|
+
${lines.join(`
|
|
6195
|
+
`)}` }],
|
|
6196
|
+
isError: reached.length === 0,
|
|
6197
|
+
details: {
|
|
6198
|
+
target,
|
|
6199
|
+
delivered: recipients.filter((recipient) => recipient.outcome === "delivered").length,
|
|
6200
|
+
recipients: recipients.map((recipient) => ({ ...recipient }))
|
|
6201
|
+
}
|
|
6202
|
+
};
|
|
6203
|
+
}
|
|
6204
|
+
var SUBAGENT_LIST_INTERCOM_CHILDREN_EVENT = "subagent:list-intercom-children", SUBAGENTS_TARGET_PREFIX = "subagents:", WORKFLOW_TARGET_PREFIX2 = "workflow:", CLOSE_NAME_LIMIT = 5;
|
|
6205
|
+
|
|
5855
6206
|
// dist/builtin/intercom/intercom-tool.ts
|
|
5856
|
-
import {
|
|
5857
|
-
|
|
6207
|
+
import {
|
|
6208
|
+
automaticWaitBudgetMs,
|
|
6209
|
+
isIntercomRoutingError,
|
|
6210
|
+
isProjectGroupError,
|
|
6211
|
+
isRetryableIntercomRoutingError
|
|
6212
|
+
} from "@bastani/atomic";
|
|
6213
|
+
import { Type as Type3 } from "typebox";
|
|
5858
6214
|
import { Text as Text3 } from "@earendil-works/pi-tui";
|
|
5859
6215
|
function retryErrorDetails(retryToken) {
|
|
5860
6216
|
return retryToken === undefined ? { error: true } : { error: true, retryToken };
|
|
@@ -5991,6 +6347,36 @@ function formatDeliveryStateSummary(stage) {
|
|
|
5991
6347
|
return `
|
|
5992
6348
|
… ${omitted} more delivery state${omitted === 1 ? "" : "s"} omitted (all: ${counts})`;
|
|
5993
6349
|
}
|
|
6350
|
+
async function describeAskRecipient(client, to, recipientId) {
|
|
6351
|
+
let session;
|
|
6352
|
+
try {
|
|
6353
|
+
const sessions = await client.listSessions();
|
|
6354
|
+
session = sessions.find((candidate) => candidate.id === recipientId) ?? sessions.find((candidate) => candidate.name !== undefined && candidate.name.toLowerCase() === to.trim().toLowerCase());
|
|
6355
|
+
} catch {
|
|
6356
|
+
session = undefined;
|
|
6357
|
+
}
|
|
6358
|
+
const name = session?.name || to;
|
|
6359
|
+
const status = session?.status?.trim();
|
|
6360
|
+
if (status === undefined || status.length === 0)
|
|
6361
|
+
return { name, state: "unknown" };
|
|
6362
|
+
const activity = status.split(" · ")[0] ?? status;
|
|
6363
|
+
if (activity === "idle")
|
|
6364
|
+
return { name, state: "idle" };
|
|
6365
|
+
return { name, state: "busy", currentAction: activity.startsWith("tool:") ? `running ${activity.slice(5)}` : activity };
|
|
6366
|
+
}
|
|
6367
|
+
function askPendingText(askId, to, recipient, stopped) {
|
|
6368
|
+
const state = recipient.state === "unknown" ? "" : recipient.state === "idle" ? " (idle)" : ` (busy${recipient.currentAction === undefined ? "" : `: ${recipient.currentAction}`})`;
|
|
6369
|
+
const prefix = stopped === undefined ? "" : `No reply yet; ${stopped}. `;
|
|
6370
|
+
return `${prefix}Ask ${askId} delivered to ${recipient.name || to}${state}. The ask stays pending: its reply will arrive later as a message starting "Reply to your ask ${askId} from ${recipient.name || to}". Continue with other work; cancel it with intercom({ action: "cancel", askId: "${askId}" }).`;
|
|
6371
|
+
}
|
|
6372
|
+
function automaticAskWaitBudgetMs(ctx) {
|
|
6373
|
+
try {
|
|
6374
|
+
const host = ctx.getAgentTaskHost?.();
|
|
6375
|
+
if (host !== undefined)
|
|
6376
|
+
return host.commandWaitBudgetMs;
|
|
6377
|
+
} catch {}
|
|
6378
|
+
return automaticWaitBudgetMs(undefined, true);
|
|
6379
|
+
}
|
|
5994
6380
|
function registerIntercomTool(pi, deps) {
|
|
5995
6381
|
const retryIdentities = new RetryIdentityReservations({ maxEntries: deps.retryIdentityMaxEntries });
|
|
5996
6382
|
const { childOrchestratorMetadata, ensureConnected, syncPresenceIdentity, beginReplyWait } = deps;
|
|
@@ -5998,6 +6384,88 @@ function registerIntercomTool(pi, deps) {
|
|
|
5998
6384
|
const resolveRecipient = async (client, target) => parseWorkflowStageTarget(target) === undefined ? await resolveTarget(client, target) ?? target : target;
|
|
5999
6385
|
const getMetadata = typeof childOrchestratorMetadata === "function" ? childOrchestratorMetadata : () => childOrchestratorMetadata ?? null;
|
|
6000
6386
|
const activeReplyTracker = () => typeof deps.replyTracker === "function" ? deps.replyTracker() : deps.replyTracker;
|
|
6387
|
+
const ownOutboundAsks = deps.outboundAsks === undefined ? new OutboundAsks({
|
|
6388
|
+
entries: () => [],
|
|
6389
|
+
append: (customType, data) => pi.appendEntry(customType, data),
|
|
6390
|
+
sessionId: () => null
|
|
6391
|
+
}) : undefined;
|
|
6392
|
+
const outboundAsks = () => ownOutboundAsks ?? (typeof deps.outboundAsks === "function" ? deps.outboundAsks() : deps.outboundAsks);
|
|
6393
|
+
const patternError = (text) => ({
|
|
6394
|
+
content: [{ type: "text", text }],
|
|
6395
|
+
isError: true,
|
|
6396
|
+
details: { error: true }
|
|
6397
|
+
});
|
|
6398
|
+
const sendToPatternTarget = async (target, pattern, request) => {
|
|
6399
|
+
if (!request.message)
|
|
6400
|
+
return patternError("Missing 'to' or 'message' parameter");
|
|
6401
|
+
if (pattern.kind === "invalid")
|
|
6402
|
+
return patternError(pattern.reason);
|
|
6403
|
+
if (request.replyTo) {
|
|
6404
|
+
return patternError(`replyTo answers one ask, so it needs one exact target; "${target}" is a pattern.`);
|
|
6405
|
+
}
|
|
6406
|
+
let recipients = [];
|
|
6407
|
+
let lookupFailure = "";
|
|
6408
|
+
const lookup = await runIntercomOperation(async () => {
|
|
6409
|
+
try {
|
|
6410
|
+
const client = await ensureConnected("tool");
|
|
6411
|
+
syncPresenceIdentity(request.toolSessionId);
|
|
6412
|
+
if (pattern.kind === "sessions") {
|
|
6413
|
+
const sessions = await client.listSessions();
|
|
6414
|
+
const matches = matchSessionPattern(sessions, pattern.pattern, client.sessionId);
|
|
6415
|
+
if (matches.length === 0) {
|
|
6416
|
+
const close = closeSessionNames(sessions, pattern.pattern, client.sessionId);
|
|
6417
|
+
return patternError(`No session visible in your groups matches "${pattern.pattern}". ${close.length === 0 ? "No other sessions are visible in your groups." : `Close names: ${close.join(", ")}.`}`);
|
|
6418
|
+
}
|
|
6419
|
+
recipients = matches.map((session) => ({
|
|
6420
|
+
target: session.id,
|
|
6421
|
+
label: session.name ? `${session.name} (${session.id})` : session.id
|
|
6422
|
+
}));
|
|
6423
|
+
} else {
|
|
6424
|
+
const children = await listIntercomChildren(pi.events, request.toolSessionId, pattern.runId);
|
|
6425
|
+
if (children.length === 0) {
|
|
6426
|
+
return patternError(`This session has no running, released or paused subagents${pattern.runId === undefined ? "" : ` in run ${pattern.runId}`} to send to.`);
|
|
6427
|
+
}
|
|
6428
|
+
recipients = children.map((child) => ({ target: child.childName, label: `${child.childName} (${child.childId})` }));
|
|
6429
|
+
}
|
|
6430
|
+
return { content: [], isError: false, details: {} };
|
|
6431
|
+
} catch (error) {
|
|
6432
|
+
const retryable = isRecoverableIntercomDisconnect(error) || isRetryableIntercomRoutingError(error);
|
|
6433
|
+
lookupFailure = getErrorMessage(error);
|
|
6434
|
+
return {
|
|
6435
|
+
content: [{ type: "text", text: `Failed to send: ${lookupFailure}` }],
|
|
6436
|
+
isError: true,
|
|
6437
|
+
details: { error: true, retryable }
|
|
6438
|
+
};
|
|
6439
|
+
}
|
|
6440
|
+
}, () => {}, request.signal);
|
|
6441
|
+
if (lookup.isError && lookup.details.terminal === true) {
|
|
6442
|
+
return patternError(`Could not find the recipients of "${target}"${lookupFailure ? `: ${lookupFailure}` : ""}. Nothing was sent.`);
|
|
6443
|
+
}
|
|
6444
|
+
if (lookup.isError)
|
|
6445
|
+
return lookup;
|
|
6446
|
+
if (deps.confirmSend && request.ctx.hasUI) {
|
|
6447
|
+
const names = recipients.map((recipient) => `- ${recipient.label}`).join(`
|
|
6448
|
+
`);
|
|
6449
|
+
const attachmentText = request.attachments?.length ? formatAttachments(request.attachments) : "";
|
|
6450
|
+
const confirmed = await request.ctx.ui.confirm("Send Message", `Send to "${target}":
|
|
6451
|
+
${names}
|
|
6452
|
+
|
|
6453
|
+
${request.message}${attachmentText}`);
|
|
6454
|
+
if (!confirmed)
|
|
6455
|
+
return { content: [{ type: "text", text: "Message cancelled by user" }], isError: false, details: {} };
|
|
6456
|
+
}
|
|
6457
|
+
const outcomes = await Promise.all(recipients.map(async (recipient) => {
|
|
6458
|
+
const result = await request.sendOne(recipient.target);
|
|
6459
|
+
const messageId = typeof result.details.messageId === "string" ? result.details.messageId : undefined;
|
|
6460
|
+
const base = { target: recipient.target, label: recipient.label, ...messageId === undefined ? {} : { messageId } };
|
|
6461
|
+
if (!result.isError)
|
|
6462
|
+
return { ...base, outcome: result.details.queued === true ? "queued" : "delivered" };
|
|
6463
|
+
const reason = typeof result.details.reason === "string" ? result.details.reason : result.content.map(({ text }) => text).join(`
|
|
6464
|
+
`);
|
|
6465
|
+
return { ...base, outcome: result.details.outcome === "unknown" ? "unknown" : "refused", reason };
|
|
6466
|
+
}));
|
|
6467
|
+
return patternSendResult(target, outcomes);
|
|
6468
|
+
};
|
|
6001
6469
|
pi.registerTool({
|
|
6002
6470
|
name: "intercom",
|
|
6003
6471
|
exposure: "model-only",
|
|
@@ -6011,7 +6479,11 @@ Sessions belong to an intercom group and can ONLY message sessions in the same g
|
|
|
6011
6479
|
cross-group sends are rejected by the broker. Ungrouped sessions share the "default" group; with multi-node routing on, a project group (project:<owner>/<repo>).
|
|
6012
6480
|
|
|
6013
6481
|
For send, live session names, exact full session IDs, and unique 8-hex session UUID prefixes
|
|
6014
|
-
remain supported.
|
|
6482
|
+
remain supported. \`send\` also takes a name glob (\`subagent-worker-*\`, or \`*\` for every session
|
|
6483
|
+
visible in your groups except you) and \`subagents:*\` (every running, released or paused subagent this
|
|
6484
|
+
session launched) or \`subagents:<runId>/*\` (those of one run). Each recipient gets its own direct send,
|
|
6485
|
+
and the result lists every recipient's outcome; a glob that matches no session is an error naming close
|
|
6486
|
+
names. Patterns never reach outside your groups. Workflow-stage targets use
|
|
6015
6487
|
\`workflow:<rootRunId>/<segment>[/<segment>...]\`; a segment may be a stage name, run id, or glob
|
|
6016
6488
|
(\`*\` matches one segment and may be embedded, while \`**\` matches any depth). Use \`intercom list\`
|
|
6017
6489
|
inside the invocation group to see live, pending, and possible future targets with queued counts.
|
|
@@ -6020,6 +6492,7 @@ stage until the root run terminates; narrower name or pattern sends likewise rea
|
|
|
6020
6492
|
A valid target outside the known set still queues and settles undeliverable at terminal only if never
|
|
6021
6493
|
delivered; the result carries \`prediction\` (\`known\`, \`predicted\` or \`unknown\`) and shows a note only
|
|
6022
6494
|
when the target looks like a typo of a known stage. Use \`ask\` only for a live, reply-capable target.
|
|
6495
|
+
${ASK_DESCRIPTION}
|
|
6023
6496
|
Stage paths win over same-named owned subgroups for send/ask; \`list\` with \`group\` continues to
|
|
6024
6497
|
select the group.
|
|
6025
6498
|
Choose \`delivery\` per send/ask by urgency. The default "steer" arrives after the recipient's current
|
|
@@ -6036,39 +6509,43 @@ Usage:
|
|
|
6036
6509
|
intercom({ action: "leave", group: "name" }) → Leave one named group
|
|
6037
6510
|
intercom({ action: "leave" }) → Return to your resolved home group
|
|
6038
6511
|
intercom({ action: "send", to: "session-name", message: "..." }) → Send message (shared group only)
|
|
6039
|
-
intercom({ action: "
|
|
6512
|
+
intercom({ action: "send", to: "subagent-worker-*", message: "..." }) → Send to every matching session
|
|
6513
|
+
intercom({ action: "send", to: "subagents:*", message: "..." }) → Send to every subagent you launched
|
|
6514
|
+
${ASK_USAGE}
|
|
6040
6515
|
intercom({ action: "send", to: "session-name", message: "...", delivery: "interrupt" }) → Cancel the recipient's current work
|
|
6041
6516
|
intercom({ action: "reply", message: "..." }) → Reply to the active or exact pending ask
|
|
6042
|
-
intercom({ action: "pending" }) → List unresolved inbound asks
|
|
6517
|
+
intercom({ action: "pending" }) → List unresolved inbound asks and your pending asks
|
|
6043
6518
|
intercom({ action: "status" }) → Show connection status and all your groups
|
|
6044
6519
|
|
|
6045
6520
|
The "join" action is additive. "default" is the shared default group; "true" and
|
|
6046
6521
|
"auto" are reserved for subagent auto-groups. Ordinary delivery requires at least
|
|
6047
6522
|
one shared membership; contact_supervisor remains the only cross-group path.`,
|
|
6048
|
-
promptSnippet:
|
|
6049
|
-
parameters:
|
|
6050
|
-
action:
|
|
6051
|
-
description: "Action: 'list', 'groups', 'join', 'leave', 'send', 'ask', 'reply', 'pending', or 'status'"
|
|
6523
|
+
promptSnippet: `Use to coordinate with other local agent sessions that share an intercom group. ${ASK_PROMPT_SNIPPET} Send/ask/reply retry reconnects internally; do not automatically repeat an unknown delivery outcome.`,
|
|
6524
|
+
parameters: Type3.Object({
|
|
6525
|
+
action: Type3.String({
|
|
6526
|
+
description: "Action: 'list', 'groups', 'join', 'leave', 'send', 'ask', 'reply', 'pending', 'cancel', or 'status'"
|
|
6052
6527
|
}),
|
|
6053
|
-
to:
|
|
6054
|
-
description: "Live session name, exact full session ID, unique 8-hex session UUID prefix, or `workflow:<rootRunId>/<segment>[/<segment>...]` path; `*` matches one segment and `**` any depth. Send queues sticky delivery for pending/future matches; `workflow:<rootRunId>/**` broadcasts to live and future stages. Use `ask` only on live targets (for 'send', 'ask', or targeted 'reply')"
|
|
6528
|
+
to: Type3.Optional(Type3.String({
|
|
6529
|
+
description: "Live session name, exact full session ID, unique 8-hex session UUID prefix, or `workflow:<rootRunId>/<segment>[/<segment>...]` path; `*` matches one segment and `**` any depth. Send also takes a session-name glob (`subagent-worker-*`, `*`) or `subagents:*` / `subagents:<runId>/*` for the subagents this session launched; ask needs one exact target. Send queues sticky delivery for pending/future matches; `workflow:<rootRunId>/**` broadcasts to live and future stages. Use `ask` only on live targets (for 'send', 'ask', or targeted 'reply')"
|
|
6055
6530
|
})),
|
|
6056
|
-
message:
|
|
6531
|
+
message: Type3.Optional(Type3.String({
|
|
6057
6532
|
description: "Message to send (for 'send', 'ask', or 'reply' action)"
|
|
6058
6533
|
})),
|
|
6059
|
-
attachments:
|
|
6060
|
-
type:
|
|
6061
|
-
name:
|
|
6062
|
-
content:
|
|
6063
|
-
language:
|
|
6534
|
+
attachments: Type3.Optional(Type3.Array(Type3.Object({
|
|
6535
|
+
type: Type3.Union([Type3.Literal("file"), Type3.Literal("snippet"), Type3.Literal("context")]),
|
|
6536
|
+
name: Type3.String(),
|
|
6537
|
+
content: Type3.String(),
|
|
6538
|
+
language: Type3.Optional(Type3.String())
|
|
6064
6539
|
}))),
|
|
6065
|
-
delivery:
|
|
6540
|
+
delivery: Type3.Optional(Type3.Union([Type3.Literal("steer"), Type3.Literal("followUp"), Type3.Literal("interrupt")], {
|
|
6066
6541
|
description: "For 'send'/'ask'; choose per message by urgency. 'steer' (default): arrives after the recipient's current tool calls, never cancelling work. 'interrupt': the recipient must stop now (urgent correction, stop order); cancels its current model call or tool call. 'followUp': can wait until the recipient finishes (low priority, after you're done)."
|
|
6067
6542
|
})),
|
|
6068
|
-
|
|
6543
|
+
wait: Type3.Optional(askWaitSchema),
|
|
6544
|
+
askId: Type3.Optional(askIdSchema),
|
|
6545
|
+
replyTo: Type3.Optional(Type3.String({
|
|
6069
6546
|
description: "Exact pending-ask message ID or unique 8-hex UUID prefix; disambiguates concurrent asks, including asks from one sender"
|
|
6070
6547
|
})),
|
|
6071
|
-
group:
|
|
6548
|
+
group: Type3.Optional(Type3.String({
|
|
6072
6549
|
description: "Group name for 'join' or optional targeted 'leave'; read-only group filter for 'list'/'status'. 'send'/'ask' use shared memberships."
|
|
6073
6550
|
}))
|
|
6074
6551
|
}),
|
|
@@ -6084,7 +6561,8 @@ one shared membership; contact_supervisor remains the only cross-group path.`,
|
|
|
6084
6561
|
const { action, to, message, replyTo, group } = params;
|
|
6085
6562
|
const deliveryOption = params.delivery === undefined || params.delivery === "steer" ? {} : { delivery: params.delivery };
|
|
6086
6563
|
const attachments = params.attachments?.map((attachment) => ({ ...attachment }));
|
|
6087
|
-
const executeAttempt = async (retryToken, _signal, retries = 0) => {
|
|
6564
|
+
const executeAttempt = async (retryToken, _signal, retries = 0, fanOutRecipient) => {
|
|
6565
|
+
const to = fanOutRecipient ?? params.to;
|
|
6088
6566
|
if (retryToken !== undefined) {
|
|
6089
6567
|
if (action !== "send" && action !== "ask" && action !== "reply") {
|
|
6090
6568
|
const error = new RetryTokenError("mismatch");
|
|
@@ -6338,7 +6816,7 @@ ${otherSection}` }],
|
|
|
6338
6816
|
expectsReply: false
|
|
6339
6817
|
});
|
|
6340
6818
|
}
|
|
6341
|
-
if (retryToken === undefined && !replyTo && deps.confirmSend && ctx.hasUI) {
|
|
6819
|
+
if (retryToken === undefined && fanOutRecipient === undefined && !replyTo && deps.confirmSend && ctx.hasUI) {
|
|
6342
6820
|
const attachmentText = attachments?.length ? formatAttachments(attachments) : "";
|
|
6343
6821
|
const confirmed = await ctx.ui.confirm("Send Message", `Send to "${to}":
|
|
6344
6822
|
|
|
@@ -6515,6 +6993,10 @@ ${message}${attachmentText}`);
|
|
|
6515
6993
|
details: retryErrorDetails(retryToken)
|
|
6516
6994
|
};
|
|
6517
6995
|
}
|
|
6996
|
+
const askWait = parseAskWait(params.wait);
|
|
6997
|
+
if (askWait instanceof Error) {
|
|
6998
|
+
return { content: [{ type: "text", text: askWait.message }], isError: true, details: { error: true } };
|
|
6999
|
+
}
|
|
6518
7000
|
let wait = null;
|
|
6519
7001
|
let retryIdentity;
|
|
6520
7002
|
let askDelivered = false;
|
|
@@ -6620,36 +7102,43 @@ ${message}${attachmentText}`);
|
|
|
6620
7102
|
};
|
|
6621
7103
|
}
|
|
6622
7104
|
const questionId = retryIdentity.messageId;
|
|
6623
|
-
|
|
6624
|
-
const
|
|
6625
|
-
|
|
6626
|
-
|
|
6627
|
-
|
|
6628
|
-
const
|
|
6629
|
-
|
|
6630
|
-
|
|
6631
|
-
|
|
6632
|
-
|
|
6633
|
-
|
|
6634
|
-
|
|
6635
|
-
|
|
6636
|
-
|
|
7105
|
+
let replyFrom = replySender.kind === "resolved" ? replySender.sessionId : sendTo;
|
|
7106
|
+
const question = message ?? "";
|
|
7107
|
+
const budgetMs = askWait?.kind === "background" ? 0 : askWait?.budgetMs !== undefined ? askWait.budgetMs : automaticAskWaitBudgetMs(ctx);
|
|
7108
|
+
outboundAsks().open({ askId: questionId, to, recipientId: replyFrom, question });
|
|
7109
|
+
if (budgetMs !== 0) {
|
|
7110
|
+
const admission = beginReplyWait(replyFrom, questionId, signal, budgetMs ?? null);
|
|
7111
|
+
if (!admission.ok && admission.reason === "cancelled") {
|
|
7112
|
+
outboundAsks().forget(questionId);
|
|
7113
|
+
const retained = retainInconclusiveRetry(retryIdentities, retryIdentity);
|
|
7114
|
+
retryIdentity = undefined;
|
|
7115
|
+
return {
|
|
7116
|
+
content: [{ type: "text", text: "Cancelled" }],
|
|
7117
|
+
isError: true,
|
|
7118
|
+
details: retryErrorDetails(retained.retryToken)
|
|
7119
|
+
};
|
|
7120
|
+
}
|
|
7121
|
+
if (admission.ok)
|
|
7122
|
+
wait = admission.wait;
|
|
6637
7123
|
}
|
|
6638
|
-
wait = admission.wait;
|
|
6639
7124
|
const sendResult = await connectedClient.send(sendTo, {
|
|
6640
7125
|
messageId: questionId,
|
|
6641
7126
|
logicalTarget: to,
|
|
6642
|
-
text:
|
|
7127
|
+
text: question,
|
|
6643
7128
|
attachments,
|
|
6644
7129
|
replyTo,
|
|
6645
7130
|
expectsReply: true,
|
|
6646
7131
|
...deliveryOption,
|
|
6647
|
-
onReplyTarget:
|
|
7132
|
+
onReplyTarget: (sender) => {
|
|
7133
|
+
replyFrom = sender;
|
|
7134
|
+
wait?.bindSender(sender);
|
|
7135
|
+
}
|
|
6648
7136
|
});
|
|
6649
7137
|
if (sendResult.queued === true) {
|
|
7138
|
+
outboundAsks().forget(questionId);
|
|
6650
7139
|
retryIdentities.release(retryIdentity);
|
|
6651
7140
|
retryIdentity = undefined;
|
|
6652
|
-
wait
|
|
7141
|
+
wait?.cancel(new Error(`Message queued for ${to}`));
|
|
6653
7142
|
await pi.appendEntry("intercom_sent", {
|
|
6654
7143
|
to,
|
|
6655
7144
|
message: { text: message, attachments, replyTo },
|
|
@@ -6669,10 +7158,11 @@ ${message}${attachmentText}`);
|
|
|
6669
7158
|
};
|
|
6670
7159
|
}
|
|
6671
7160
|
if (!sendResult.delivered) {
|
|
7161
|
+
outboundAsks().forget(questionId);
|
|
6672
7162
|
const retained = retainInconclusiveRetry(retryIdentities, retryIdentity);
|
|
6673
7163
|
retryIdentity = undefined;
|
|
6674
7164
|
const errorText = sendResult.reason ?? "Session may not exist or has disconnected.";
|
|
6675
|
-
wait
|
|
7165
|
+
wait?.cancel(new Error(`Message to "${to}" was not delivered: ${errorText}`));
|
|
6676
7166
|
const pendingStageAskRefusal = errorText.startsWith("Cannot ask a workflow stage whose session has not initialized.");
|
|
6677
7167
|
return {
|
|
6678
7168
|
content: [{
|
|
@@ -6691,16 +7181,48 @@ ${message}${attachmentText}`);
|
|
|
6691
7181
|
};
|
|
6692
7182
|
}
|
|
6693
7183
|
askDelivered = true;
|
|
7184
|
+
retryIdentities.release(retryIdentity);
|
|
7185
|
+
retryIdentity = undefined;
|
|
7186
|
+
outboundAsks().open({ askId: questionId, to, recipientId: replyFrom, question });
|
|
6694
7187
|
await pi.appendEntry("intercom_sent", {
|
|
6695
7188
|
to,
|
|
6696
7189
|
message: { text: message, attachments, replyTo },
|
|
6697
7190
|
messageId: sendResult.id,
|
|
6698
7191
|
timestamp: Date.now()
|
|
6699
7192
|
});
|
|
6700
|
-
await
|
|
6701
|
-
const
|
|
6702
|
-
|
|
6703
|
-
|
|
7193
|
+
await outboundAsks().persist(questionId);
|
|
7194
|
+
const recipient = await describeAskRecipient(connectedClient, to, replyFrom);
|
|
7195
|
+
const pendingResult = (stopped) => ({
|
|
7196
|
+
content: [{
|
|
7197
|
+
type: "text",
|
|
7198
|
+
text: askPendingText(questionId, to, recipient, stopped)
|
|
7199
|
+
}],
|
|
7200
|
+
isError: false,
|
|
7201
|
+
details: { askId: questionId, delivered: true, recipient, pending: true }
|
|
7202
|
+
});
|
|
7203
|
+
if (wait === null)
|
|
7204
|
+
return pendingResult();
|
|
7205
|
+
const activeWait = wait;
|
|
7206
|
+
if (budgetMs !== undefined) {
|
|
7207
|
+
await prepareReleasedReplyWait(pi, activeWait, signal, { toolCallId, questionId, from: replyFrom, retryCount: retries }, () => deps.mayDetachReplyWait?.() === true);
|
|
7208
|
+
}
|
|
7209
|
+
let replyMessage;
|
|
7210
|
+
try {
|
|
7211
|
+
replyMessage = await activeWait.promise;
|
|
7212
|
+
} catch (waitError) {
|
|
7213
|
+
if (waitError instanceof ReleasedReplyHandoff)
|
|
7214
|
+
throw waitError;
|
|
7215
|
+
if (waitError instanceof PeerDisconnectedError) {
|
|
7216
|
+
await outboundAsks().settle(questionId, "failed");
|
|
7217
|
+
return {
|
|
7218
|
+
content: [{ type: "text", text: `Failed: ${getErrorMessage(waitError)}` }],
|
|
7219
|
+
isError: true,
|
|
7220
|
+
details: { error: true, askId: questionId }
|
|
7221
|
+
};
|
|
7222
|
+
}
|
|
7223
|
+
return pendingResult(signal?.aborted === true ? "stopped waiting" : "the wait budget ended");
|
|
7224
|
+
}
|
|
7225
|
+
await outboundAsks().settle(questionId, replyMessage.replyError === undefined ? "answered" : "failed");
|
|
6704
7226
|
const replyText = replyMessage.content.text;
|
|
6705
7227
|
const replyAttachments = replyMessage.content.attachments?.length ? formatAttachments(replyMessage.content.attachments) : "";
|
|
6706
7228
|
await appendEntryUnlessReleased(pi, "intercom_received", {
|
|
@@ -6713,14 +7235,14 @@ ${message}${attachmentText}`);
|
|
|
6713
7235
|
return {
|
|
6714
7236
|
content: [{ type: "text", text: `Failed: ${replyMessage.replyError}` }],
|
|
6715
7237
|
isError: true,
|
|
6716
|
-
details: { error: true, replyTo: replyMessage.replyTo }
|
|
7238
|
+
details: { error: true, askId: questionId, replyTo: replyMessage.replyTo }
|
|
6717
7239
|
};
|
|
6718
7240
|
}
|
|
6719
7241
|
return {
|
|
6720
7242
|
content: [{ type: "text", text: `**Reply from ${to}:**
|
|
6721
7243
|
${replyText}${replyAttachments}` }],
|
|
6722
7244
|
isError: false,
|
|
6723
|
-
details: {}
|
|
7245
|
+
details: { askId: questionId, delivered: true, recipient, replied: true }
|
|
6724
7246
|
};
|
|
6725
7247
|
} catch (error) {
|
|
6726
7248
|
if (error instanceof ReleasedReplyHandoff) {
|
|
@@ -6729,6 +7251,8 @@ ${replyText}${replyAttachments}` }],
|
|
|
6729
7251
|
return releasedReplyHandoffResult();
|
|
6730
7252
|
}
|
|
6731
7253
|
wait?.cancel(toError(error));
|
|
7254
|
+
if (!askDelivered && retryIdentity !== undefined)
|
|
7255
|
+
outboundAsks().forget(retryIdentity.messageId);
|
|
6732
7256
|
let failure = error;
|
|
6733
7257
|
let retained;
|
|
6734
7258
|
if (retryIdentity !== undefined) {
|
|
@@ -6850,8 +7374,12 @@ ${replyText}${replyAttachments}` }],
|
|
|
6850
7374
|
timestamp: Date.now()
|
|
6851
7375
|
});
|
|
6852
7376
|
activeReplyTracker().markReplied(route.messageId);
|
|
7377
|
+
const heldForAsker = result.target === HELD_FOR_AWAY_ASKER_TARGET || result.target === OFFLINE_SESSION_TARGET;
|
|
6853
7378
|
return {
|
|
6854
|
-
content: [{
|
|
7379
|
+
content: [{
|
|
7380
|
+
type: "text",
|
|
7381
|
+
text: heldForAsker ? `Reply delivered (held for ${displayTarget} until it is back)` : `Reply queued for ${displayTarget}`
|
|
7382
|
+
}],
|
|
6855
7383
|
isError: false,
|
|
6856
7384
|
details: {
|
|
6857
7385
|
messageId: result.id,
|
|
@@ -6920,25 +7448,58 @@ ${replyText}${replyAttachments}` }],
|
|
|
6920
7448
|
}
|
|
6921
7449
|
case "pending": {
|
|
6922
7450
|
const pendingAsks = activeReplyTracker().listPending();
|
|
6923
|
-
|
|
7451
|
+
const outbound = outboundAsks().pending();
|
|
7452
|
+
if (pendingAsks.length === 0 && outbound.length === 0) {
|
|
6924
7453
|
return {
|
|
6925
|
-
content: [{ type: "text", text: "No unresolved inbound asks." }],
|
|
7454
|
+
content: [{ type: "text", text: "No unresolved inbound or outbound asks." }],
|
|
6926
7455
|
isError: false,
|
|
6927
|
-
details: {}
|
|
7456
|
+
details: { outbound: [] }
|
|
6928
7457
|
};
|
|
6929
7458
|
}
|
|
6930
7459
|
const now = Date.now();
|
|
6931
|
-
const
|
|
6932
|
-
|
|
6933
|
-
|
|
6934
|
-
|
|
6935
|
-
|
|
6936
|
-
|
|
6937
|
-
|
|
7460
|
+
const elapsed = (since) => `${Math.max(0, Math.floor((now - since) / 1000))}s ago`;
|
|
7461
|
+
const sections = [];
|
|
7462
|
+
if (pendingAsks.length > 0) {
|
|
7463
|
+
const lines = pendingAsks.map(({ from, message, receivedAt }) => {
|
|
7464
|
+
const preview = message.content.text.replace(/\s+/g, " ").slice(0, 80);
|
|
7465
|
+
return `- ${from.name || from.id} · ${message.id} · ${elapsed(receivedAt)} · ${preview}`;
|
|
7466
|
+
});
|
|
7467
|
+
sections.push(`**Pending asks:**
|
|
6938
7468
|
${lines.join(`
|
|
6939
|
-
`)}`
|
|
7469
|
+
`)}`);
|
|
7470
|
+
}
|
|
7471
|
+
if (outbound.length > 0) {
|
|
7472
|
+
const lines = outbound.map(({ askId, to, question, askedAt }) => `- ${askId} → ${to} · ${elapsed(askedAt)} · ${question.replace(/\s+/g, " ").slice(0, 80)}`);
|
|
7473
|
+
sections.push(`**Your asks awaiting a reply:**
|
|
7474
|
+
${lines.join(`
|
|
7475
|
+
`)}`);
|
|
7476
|
+
}
|
|
7477
|
+
return {
|
|
7478
|
+
content: [{ type: "text", text: sections.join(`
|
|
7479
|
+
|
|
7480
|
+
`) }],
|
|
7481
|
+
isError: false,
|
|
7482
|
+
details: { outbound: outbound.map(({ askId, to, askedAt }) => ({ askId, to, askedAt })) }
|
|
7483
|
+
};
|
|
7484
|
+
}
|
|
7485
|
+
case "cancel": {
|
|
7486
|
+
const requested = typeof params.askId === "string" ? params.askId.trim() : "";
|
|
7487
|
+
if (!requested) {
|
|
7488
|
+
return { content: [{ type: "text", text: "Missing 'askId' parameter" }], isError: true, details: { error: true } };
|
|
7489
|
+
}
|
|
7490
|
+
const matches = outboundAsks().pending().filter(({ askId }) => askId === requested || askId.startsWith(requested));
|
|
7491
|
+
const exact = matches.find(({ askId }) => askId === requested);
|
|
7492
|
+
const target = exact ?? (matches.length === 1 ? matches[0] : undefined);
|
|
7493
|
+
if (target === undefined) {
|
|
7494
|
+
const text = matches.length > 1 ? `"${requested}" matches several pending asks; use the full ask id` : `No pending ask "${requested}"`;
|
|
7495
|
+
return { content: [{ type: "text", text }], isError: true, details: { error: true } };
|
|
7496
|
+
}
|
|
7497
|
+
deps.cancelReplyWait?.(target.askId);
|
|
7498
|
+
await outboundAsks().settle(target.askId, "cancelled");
|
|
7499
|
+
return {
|
|
7500
|
+
content: [{ type: "text", text: `Cancelled ask ${target.askId} to ${target.to}. A reply that still arrives is shown once, marked late.` }],
|
|
6940
7501
|
isError: false,
|
|
6941
|
-
details: {}
|
|
7502
|
+
details: { askId: target.askId, cancelled: true }
|
|
6942
7503
|
};
|
|
6943
7504
|
}
|
|
6944
7505
|
case "status": {
|
|
@@ -6960,7 +7521,8 @@ Multi-node routing: ${multiNode.line}`;
|
|
|
6960
7521
|
Connected: Yes
|
|
6961
7522
|
Session ID: ${mySessionId}
|
|
6962
7523
|
Groups: ${ownGroups.join(", ")}
|
|
6963
|
-
Active visible sessions: ${sessions.length}${selectedSection}${multiNodeSection}
|
|
7524
|
+
Active visible sessions: ${sessions.length}${selectedSection}${multiNodeSection}
|
|
7525
|
+
Your asks awaiting a reply: ${outboundAsks().pending().length}`
|
|
6964
7526
|
}],
|
|
6965
7527
|
isError: false,
|
|
6966
7528
|
details: {
|
|
@@ -6986,6 +7548,25 @@ Active visible sessions: ${sessions.length}${selectedSection}${multiNodeSection}
|
|
|
6986
7548
|
};
|
|
6987
7549
|
}
|
|
6988
7550
|
};
|
|
7551
|
+
const sendPattern = (action === "send" || action === "ask") && typeof to === "string" ? parseSendPatternTarget(to) : undefined;
|
|
7552
|
+
if (sendPattern !== undefined && action === "ask") {
|
|
7553
|
+
return {
|
|
7554
|
+
content: [{ type: "text", text: `ask needs one exact target, and "${to}" is a pattern: a reply to a broadcast question would be ambiguous. Use send to reach every match, or ask each recipient by its exact name.` }],
|
|
7555
|
+
isError: true,
|
|
7556
|
+
details: { error: true }
|
|
7557
|
+
};
|
|
7558
|
+
}
|
|
7559
|
+
if (sendPattern !== undefined && typeof to === "string") {
|
|
7560
|
+
return sendToPatternTarget(to, sendPattern, {
|
|
7561
|
+
message,
|
|
7562
|
+
replyTo,
|
|
7563
|
+
toolSessionId,
|
|
7564
|
+
attachments,
|
|
7565
|
+
signal,
|
|
7566
|
+
ctx,
|
|
7567
|
+
sendOne: (recipient) => runIntercomOperation((token, attemptSignal, retries) => executeAttempt(token, attemptSignal, retries, recipient), (token) => retryIdentities.discard(token), signal)
|
|
7568
|
+
});
|
|
7569
|
+
}
|
|
6989
7570
|
if (action !== "send" && action !== "ask" && action !== "reply")
|
|
6990
7571
|
return executeAttempt(undefined, signal);
|
|
6991
7572
|
return runIntercomOperation(executeAttempt, (token) => retryIdentities.discard(token), signal);
|
|
@@ -7013,6 +7594,9 @@ Active visible sessions: ${sessions.length}${selectedSection}${multiNodeSection}
|
|
|
7013
7594
|
});
|
|
7014
7595
|
}
|
|
7015
7596
|
var init_intercom_tool = __esm(() => {
|
|
7597
|
+
init_outbound_asks();
|
|
7598
|
+
init_ask_wait();
|
|
7599
|
+
init_peer_disconnect_routing();
|
|
7016
7600
|
init_broker_status();
|
|
7017
7601
|
init_detachable_calls();
|
|
7018
7602
|
init_parent_ask_handoff();
|
|
@@ -7454,7 +8038,7 @@ function registerIntercomLifecycle(pi, deps) {
|
|
|
7454
8038
|
deps.setClient(null);
|
|
7455
8039
|
if (activeClient) {
|
|
7456
8040
|
try {
|
|
7457
|
-
await activeClient.disconnect();
|
|
8041
|
+
await activeClient.disconnect({ resumable: deps.sessionResumable?.() === true });
|
|
7458
8042
|
} catch (error) {
|
|
7459
8043
|
if (!reportOwnedIntercomDiagnostic())
|
|
7460
8044
|
console.error(`Intercom failed to disconnect during ${reason.toLowerCase()}; continuing cleanup:`, error);
|
|
@@ -8630,7 +9214,7 @@ var INTERCOM_DETACH_REQUEST_EVENT = "pi-intercom:detach-request", INTERCOM_DETAC
|
|
|
8630
9214
|
var init_foreground_detach_handoff = () => {};
|
|
8631
9215
|
|
|
8632
9216
|
// dist/builtin/intercom/reply-routing.ts
|
|
8633
|
-
function
|
|
9217
|
+
function matches2(waiter, from, message) {
|
|
8634
9218
|
const senderTarget = from.name || from.id;
|
|
8635
9219
|
const fromMatches = senderTarget.toLowerCase() === waiter.from.toLowerCase() || from.id === waiter.from;
|
|
8636
9220
|
return fromMatches && message.replyTo === waiter.replyTo;
|
|
@@ -8640,7 +9224,7 @@ function routeIncomingReply(waiters, from, message) {
|
|
|
8640
9224
|
return false;
|
|
8641
9225
|
const candidates = Symbol.iterator in Object(waiters) ? waiters : [waiters];
|
|
8642
9226
|
for (const waiter of candidates) {
|
|
8643
|
-
if (!
|
|
9227
|
+
if (!matches2(waiter, from, message))
|
|
8644
9228
|
continue;
|
|
8645
9229
|
waiter.resolve(message);
|
|
8646
9230
|
return true;
|
|
@@ -8648,25 +9232,6 @@ function routeIncomingReply(waiters, from, message) {
|
|
|
8648
9232
|
return false;
|
|
8649
9233
|
}
|
|
8650
9234
|
|
|
8651
|
-
// dist/builtin/intercom/peer-disconnect-routing.ts
|
|
8652
|
-
function matches2(waiter, notice) {
|
|
8653
|
-
const peerTarget = notice.peerName || notice.peerSessionId;
|
|
8654
|
-
const peerMatches = peerTarget.toLowerCase() === waiter.from.toLowerCase() || notice.peerSessionId === waiter.from;
|
|
8655
|
-
return peerMatches && notice.replyTo === waiter.replyTo;
|
|
8656
|
-
}
|
|
8657
|
-
function routePeerDisconnect(waiters, notice) {
|
|
8658
|
-
if (!waiters)
|
|
8659
|
-
return false;
|
|
8660
|
-
const candidates = Symbol.iterator in Object(waiters) ? waiters : [waiters];
|
|
8661
|
-
for (const waiter of candidates) {
|
|
8662
|
-
if (!matches2(waiter, notice))
|
|
8663
|
-
continue;
|
|
8664
|
-
waiter.reject(new Error(`Session "${notice.peerName ?? notice.peerSessionId}" disconnected before replying`));
|
|
8665
|
-
return true;
|
|
8666
|
-
}
|
|
8667
|
-
return false;
|
|
8668
|
-
}
|
|
8669
|
-
|
|
8670
9235
|
// dist/builtin/intercom/incoming-message-delivery.ts
|
|
8671
9236
|
function createIncomingMessageSender(input) {
|
|
8672
9237
|
return (entry, requested, generation = input.currentGeneration(), trackReplyContext = true, turnContext, stageAdmissionBarrier) => {
|
|
@@ -8734,9 +9299,10 @@ function buildIncomingCustomMessage(entry) {
|
|
|
8734
9299
|
const replyInstruction = entry.replyCommand ? `
|
|
8735
9300
|
|
|
8736
9301
|
To reply, use the intercom tool: ${entry.replyCommand}` : "";
|
|
9302
|
+
const opening = entry.heading ?? `**\uD83D\uDCE8 From ${senderDisplay}** (${entry.from.cwd})`;
|
|
8737
9303
|
return {
|
|
8738
9304
|
customType: "intercom_message",
|
|
8739
|
-
content:
|
|
9305
|
+
content: `${opening}${replyInstruction}
|
|
8740
9306
|
|
|
8741
9307
|
${entry.bodyText}`,
|
|
8742
9308
|
display: true,
|
|
@@ -9843,19 +10409,28 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
9843
10409
|
}
|
|
9844
10410
|
}
|
|
9845
10411
|
const pendingIdleMessages = new InboundIdleQueue(() => consumedIntercomMessageIds(sessionBranch()));
|
|
10412
|
+
function sessionIsSaved() {
|
|
10413
|
+
try {
|
|
10414
|
+
return runtimeContext?.sessionManager.getSessionStore?.().descriptor.adapter !== "memory";
|
|
10415
|
+
} catch {
|
|
10416
|
+
return true;
|
|
10417
|
+
}
|
|
10418
|
+
}
|
|
9846
10419
|
const durableInbox = new DurableInbox({
|
|
9847
|
-
durable:
|
|
9848
|
-
try {
|
|
9849
|
-
return runtimeContext?.sessionManager.getSessionStore?.().descriptor.adapter !== "memory";
|
|
9850
|
-
} catch {
|
|
9851
|
-
return true;
|
|
9852
|
-
}
|
|
9853
|
-
},
|
|
10420
|
+
durable: sessionIsSaved,
|
|
9854
10421
|
entries: sessionBranch,
|
|
9855
10422
|
append: (record) => pi.appendEntry(INTERCOM_INBOX_ENTRY, record),
|
|
9856
10423
|
appendHandled: (messageId) => pi.appendEntry(INTERCOM_INBOX_HANDLED_ENTRY, { messageId })
|
|
9857
10424
|
});
|
|
9858
10425
|
const inboundDeliveries = new InboundMessageAdmission;
|
|
10426
|
+
const outboundAsks = new OutboundAsks({
|
|
10427
|
+
entries: sessionBranch,
|
|
10428
|
+
append: (customType, data) => pi.appendEntry(customType, data),
|
|
10429
|
+
sessionId: () => currentSessionId
|
|
10430
|
+
});
|
|
10431
|
+
function outboundAskFor(from, message) {
|
|
10432
|
+
return outboundAsks.answeredBy(from, message);
|
|
10433
|
+
}
|
|
9859
10434
|
const pendingStageRoutes = new Map;
|
|
9860
10435
|
const launcherCapabilities = new Map;
|
|
9861
10436
|
const launcherCapabilityFor = (runId) => {
|
|
@@ -10186,6 +10761,9 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
10186
10761
|
const bodyText = `${message.content.text}${attachmentText}`;
|
|
10187
10762
|
const replyCommand = config.replyHint && message.expectsReply ? `intercom({ action: "reply", message: "..." })` : undefined;
|
|
10188
10763
|
const rawEntry = { from, message, replyCommand, bodyText, ...channel ? { channel } : {} };
|
|
10764
|
+
const ask = outboundAskFor(from, message);
|
|
10765
|
+
if (ask !== undefined)
|
|
10766
|
+
return frameOutboundAskReply(rawEntry, ask);
|
|
10189
10767
|
return isDeliveryFeedback(message) ? frameDeliveryFeedback(rawEntry) : frameHistoricalSupervisorUpdate(rawEntry);
|
|
10190
10768
|
}
|
|
10191
10769
|
function receiveIncomingMessage(receiver, from, message, channel) {
|
|
@@ -10242,6 +10820,9 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
10242
10820
|
const admission = inboundDeliveries.admit(record.from, record.message);
|
|
10243
10821
|
if (admission.kind !== "reserved")
|
|
10244
10822
|
continue;
|
|
10823
|
+
const askReply = outboundAskFor(record.from, record.message);
|
|
10824
|
+
if (askReply !== undefined)
|
|
10825
|
+
outboundAsks.settle(askReply.ask.askId, record.message.replyError === undefined ? "answered" : "failed");
|
|
10245
10826
|
replyTracker.recordIncomingMessage(record.from, record.message);
|
|
10246
10827
|
if (pendingIdleMessages.enqueue(entry))
|
|
10247
10828
|
queued += 1;
|
|
@@ -10286,7 +10867,10 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
10286
10867
|
inboundDeliveries.commit(reservation);
|
|
10287
10868
|
return;
|
|
10288
10869
|
}
|
|
10289
|
-
|
|
10870
|
+
const askReply = outboundAskFor(from, message);
|
|
10871
|
+
if (askReply !== undefined)
|
|
10872
|
+
outboundAsks.settle(askReply.ask.askId, message.replyError === undefined ? "answered" : "failed");
|
|
10873
|
+
if (isDeliveryFeedback(message) && askReply === undefined) {
|
|
10290
10874
|
return retryStableDelivery({
|
|
10291
10875
|
deliver: () => sendIncomingMessage(entry, "prelude", messageGeneration, false),
|
|
10292
10876
|
isCurrent: () => Boolean(getLiveContext(liveContext, messageGeneration))
|
|
@@ -10335,6 +10919,11 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
10335
10919
|
release(new Error("Intercom session retired before inbound delivery"));
|
|
10336
10920
|
return;
|
|
10337
10921
|
}
|
|
10922
|
+
if (askReply !== undefined) {
|
|
10923
|
+
await retryStableDelivery({ deliver: () => sendIncomingMessage(entry, "trigger", messageGeneration, false), isCurrent: () => Boolean(getLiveContext(liveContext, messageGeneration)) });
|
|
10924
|
+
commit();
|
|
10925
|
+
return;
|
|
10926
|
+
}
|
|
10338
10927
|
if (!activeContext.isIdle() && !activeContext.getAgentTaskHost?.().hasActiveTaskWaits) {
|
|
10339
10928
|
if (!activeContext.hasUI) {
|
|
10340
10929
|
const activeClient = client;
|
|
@@ -10515,7 +11104,7 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
10515
11104
|
const request = { childName: notice.childName, replyTo: notice.replyTo, message: notice.message };
|
|
10516
11105
|
if (client === nextClient && getLiveContext())
|
|
10517
11106
|
pi.events.emit(RELEASED_CHILD_REPLY_EVENT, request);
|
|
10518
|
-
(request.completion ?? Promise.resolve(false)).then((accepted) => nextClient.acknowledgeReleasedChildReply(notice, accepted), () => nextClient.acknowledgeReleasedChildReply(notice, false));
|
|
11107
|
+
(request.completion ?? Promise.resolve(false)).then((accepted) => nextClient.acknowledgeReleasedChildReply(notice, accepted === true, accepted === "deliver"), () => nextClient.acknowledgeReleasedChildReply(notice, false));
|
|
10519
11108
|
});
|
|
10520
11109
|
nextClient.on("restoring_recipient_wake", (notice) => {
|
|
10521
11110
|
const wake = { childName: notice.childName };
|
|
@@ -10532,7 +11121,25 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
10532
11121
|
if (client !== nextClient) {
|
|
10533
11122
|
return;
|
|
10534
11123
|
}
|
|
10535
|
-
routePeerDisconnect(replyWaiters.pending(), notice)
|
|
11124
|
+
if (routePeerDisconnect(replyWaiters.pending(), notice))
|
|
11125
|
+
return;
|
|
11126
|
+
const record = outboundAsks.find(notice.replyTo);
|
|
11127
|
+
if (record === undefined || record.state !== "pending")
|
|
11128
|
+
return;
|
|
11129
|
+
const liveContext = getLiveContext();
|
|
11130
|
+
if (!liveContext)
|
|
11131
|
+
return;
|
|
11132
|
+
const generation = runtimeGeneration;
|
|
11133
|
+
const entry = recipientClosedAskEntry(record.ask, { sessionId: notice.peerSessionId, ...notice.peerName === undefined ? {} : { name: notice.peerName } });
|
|
11134
|
+
durableInbox.receive(entry.from, entry.message, undefined, () => {}).then(async (arrival) => {
|
|
11135
|
+
if (arrival !== "fresh")
|
|
11136
|
+
return;
|
|
11137
|
+
await retryStableDelivery({
|
|
11138
|
+
deliver: () => sendIncomingMessage(entry, "trigger", generation, false),
|
|
11139
|
+
isCurrent: () => Boolean(getLiveContext(liveContext, generation))
|
|
11140
|
+
});
|
|
11141
|
+
await outboundAsks.settle(record.ask.askId, "failed");
|
|
11142
|
+
}).catch(() => {});
|
|
10536
11143
|
});
|
|
10537
11144
|
nextClient.on("peer_rebound", (notice) => {
|
|
10538
11145
|
if (client !== nextClient)
|
|
@@ -11140,6 +11747,7 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
11140
11747
|
});
|
|
11141
11748
|
registerIntercomLifecycle(pi, {
|
|
11142
11749
|
config,
|
|
11750
|
+
sessionResumable: () => runtimeContext !== null && sessionIsSaved(),
|
|
11143
11751
|
client: () => client,
|
|
11144
11752
|
disconnectAuxiliaryClients: async () => {
|
|
11145
11753
|
await disconnectPendingStageRouteClients();
|
|
@@ -11215,6 +11823,9 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
11215
11823
|
replyTracker: () => replyTracker,
|
|
11216
11824
|
bindReplyTracker: (ctx) => {
|
|
11217
11825
|
replyTracker = bindWorkflowReplyTracker(ctx, replyTracker);
|
|
11826
|
+
try {
|
|
11827
|
+
restorePendingInboundAsks(replyTracker, ctx.sessionManager.getBranch(), ctx.sessionManager.getSessionId());
|
|
11828
|
+
} catch {}
|
|
11218
11829
|
},
|
|
11219
11830
|
preserveReplyTrackerOnCleanup: () => preserveWorkflowReplyTracker(runtimeContext),
|
|
11220
11831
|
pendingIdleMessages,
|
|
@@ -11272,7 +11883,7 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
11272
11883
|
const details = message.details;
|
|
11273
11884
|
if (!details)
|
|
11274
11885
|
return;
|
|
11275
|
-
return new InlineMessageComponent(details.from, details.message, theme, details.replyCommand, details.bodyText);
|
|
11886
|
+
return new InlineMessageComponent(details.from, details.message, theme, details.replyCommand, details.bodyText, details.heading);
|
|
11276
11887
|
});
|
|
11277
11888
|
const replyWaits = replyWaitGates(() => client);
|
|
11278
11889
|
registerContactSupervisorTool(pi, {
|
|
@@ -11287,7 +11898,7 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
11287
11898
|
childOrchestratorMetadata: currentChildOrchestratorMetadata,
|
|
11288
11899
|
ensureConnected,
|
|
11289
11900
|
syncPresenceIdentity,
|
|
11290
|
-
beginReplyWait: (from, replyTo, signal) => replyWaiters.begin(from, replyTo, signal),
|
|
11901
|
+
beginReplyWait: (from, replyTo, signal, timeoutMs) => replyWaiters.begin(from, replyTo, signal, timeoutMs),
|
|
11291
11902
|
...replyWaits,
|
|
11292
11903
|
confirmSend: config.confirmSend,
|
|
11293
11904
|
homeGroup: resolveSessionHomeGroup,
|
|
@@ -11300,7 +11911,9 @@ function piIntercomExtension(pi, testOverrides = {}) {
|
|
|
11300
11911
|
clearJoinedGroups();
|
|
11301
11912
|
await persistJoinedGroups(null);
|
|
11302
11913
|
},
|
|
11303
|
-
replyTracker: () => replyTracker
|
|
11914
|
+
replyTracker: () => replyTracker,
|
|
11915
|
+
outboundAsks,
|
|
11916
|
+
cancelReplyWait: (askId) => replyWaiters.cancel(askId, new Error("Ask cancelled"))
|
|
11304
11917
|
});
|
|
11305
11918
|
registerIntercomOverlay(pi, {
|
|
11306
11919
|
runtimeGeneration: () => runtimeGeneration,
|
|
@@ -11322,6 +11935,7 @@ var init_index_heavy = __esm(() => {
|
|
|
11322
11935
|
init_config();
|
|
11323
11936
|
init_reply_tracker();
|
|
11324
11937
|
init_reply_waiter();
|
|
11938
|
+
init_outbound_asks();
|
|
11325
11939
|
init_released_reply_wait();
|
|
11326
11940
|
init_contact_supervisor_tool();
|
|
11327
11941
|
init_intercom_tool();
|
|
@@ -11329,6 +11943,7 @@ var init_index_heavy = __esm(() => {
|
|
|
11329
11943
|
init_lifecycle();
|
|
11330
11944
|
init_subagent_relay();
|
|
11331
11945
|
init_foreground_detach_handoff();
|
|
11946
|
+
init_peer_disconnect_routing();
|
|
11332
11947
|
init_intercom_utils();
|
|
11333
11948
|
init_incoming_message_delivery();
|
|
11334
11949
|
init_inbound_idle_queue();
|
|
@@ -11366,7 +11981,7 @@ var init_index_heavy = __esm(() => {
|
|
|
11366
11981
|
init_diagnostics();
|
|
11367
11982
|
import { APP_NAME as APP_NAME2, getEnvValue } from "@bastani/atomic";
|
|
11368
11983
|
import { Text as Text4 } from "@earendil-works/pi-tui";
|
|
11369
|
-
import { Type as
|
|
11984
|
+
import { Type as Type4 } from "typebox";
|
|
11370
11985
|
|
|
11371
11986
|
// dist/builtin/intercom/context-owner.ts
|
|
11372
11987
|
var CONTEXT_OWNERS_KEY = Symbol.for("atomic-coding-agent/extension-context-owners@1");
|
|
@@ -11526,19 +12141,20 @@ function isReleasedReplyFormatRequest(payload) {
|
|
|
11526
12141
|
const request = payload;
|
|
11527
12142
|
return typeof request.toolName === "string" && typeof request.args === "object" && request.args !== null && typeof request.outcome === "object" && request.outcome !== null;
|
|
11528
12143
|
}
|
|
11529
|
-
function formatTimeout(toolName, from
|
|
12144
|
+
function formatTimeout(toolName, from) {
|
|
12145
|
+
if (toolName === "intercom")
|
|
12146
|
+
return {
|
|
12147
|
+
content: [{ type: "text", text: `No reply from "${from}" yet; stopped waiting. The ask stays pending.` }],
|
|
12148
|
+
details: { pending: true },
|
|
12149
|
+
isError: false
|
|
12150
|
+
};
|
|
11530
12151
|
const reason = `Failed: No reply from "${from}" within ${Math.round(ASK_REPLY_TIMEOUT_MS / 60000)} minutes`;
|
|
11531
|
-
|
|
11532
|
-
return {
|
|
11533
|
-
content: [{ type: "text", text: intercom ? intercomRecoveryStoppedText(reason, retryCount) : reason }],
|
|
11534
|
-
details: intercom ? { error: true, terminal: true, automaticRetries: retryCount, outcome: "unknown" } : { error: true },
|
|
11535
|
-
isError: true
|
|
11536
|
-
};
|
|
12152
|
+
return { content: [{ type: "text", text: reason }], details: { error: true }, isError: true };
|
|
11537
12153
|
}
|
|
11538
12154
|
function formatReleasedReply(request) {
|
|
11539
12155
|
const { toolName, args, outcome } = request;
|
|
11540
12156
|
if (outcome.kind === "timeout")
|
|
11541
|
-
return { ok: true, formatted: formatTimeout(toolName, outcome.from
|
|
12157
|
+
return { ok: true, formatted: formatTimeout(toolName, outcome.from) };
|
|
11542
12158
|
const reply = outcome.reply;
|
|
11543
12159
|
const attachments = reply.attachments?.length ? formatAttachments(reply.attachments) : "";
|
|
11544
12160
|
if (toolName === "intercom") {
|
|
@@ -11591,6 +12207,7 @@ function answerReleasedReplyFormatRequests(events) {
|
|
|
11591
12207
|
}
|
|
11592
12208
|
|
|
11593
12209
|
// dist/builtin/intercom/index.ts
|
|
12210
|
+
init_ask_wait();
|
|
11594
12211
|
init_durable_inbox();
|
|
11595
12212
|
|
|
11596
12213
|
// dist/builtin/intercom/lazy-heavy-proxy.ts
|
|
@@ -12047,10 +12664,10 @@ function intercom(pi, options = {}) {
|
|
|
12047
12664
|
label: "Contact Supervisor",
|
|
12048
12665
|
description: "Subagent-only tool for contacting the supervisor agent that delegated this task.",
|
|
12049
12666
|
promptSnippet: "Subagent-only: contact the supervisor for decisions, interviews, or meaningful updates.",
|
|
12050
|
-
parameters:
|
|
12051
|
-
reason:
|
|
12052
|
-
message:
|
|
12053
|
-
interview:
|
|
12667
|
+
parameters: Type4.Object({
|
|
12668
|
+
reason: Type4.String({ enum: ["need_decision", "progress_update", "interview_request"] }),
|
|
12669
|
+
message: Type4.Optional(Type4.String()),
|
|
12670
|
+
interview: Type4.Optional(Type4.Unknown())
|
|
12054
12671
|
}),
|
|
12055
12672
|
execute: (...args) => executeHeavyTool(loadHeavy, "contact_supervisor", args),
|
|
12056
12673
|
renderResult: (...args) => renderHeavyToolResult(loadedHeavy?.heavy ?? null, "contact_supervisor", args)
|
|
@@ -12434,7 +13051,8 @@ function intercom(pi, options = {}) {
|
|
|
12434
13051
|
description: `Send a message to another local agent session running on this machine.
|
|
12435
13052
|
Use this to communicate findings, request help, or coordinate work with other sessions.
|
|
12436
13053
|
Sessions belong to an intercom group and can ONLY message sessions in the same group; cross-group sends are rejected by the broker. Ungrouped sessions share the "default" group; with multi-node routing on, a project group (project:<owner>/<repo>).
|
|
12437
|
-
For send, live session names, exact full session IDs, and unique 8-hex session UUID prefixes remain supported. Workflow-stage targets use \`workflow:<rootRunId>/<segment>[/<segment>...]\`; \`*\` matches one segment and \`**\` any depth. Use \`intercom list\` inside the invocation group to see live, pending, and possible future targets with queued counts. \`workflow:<rootRunId>/**\` reaches live stages now and remains sticky for every future stage until root termination; valid targets outside the known set still queue and settle undeliverable at terminal only if never delivered; a note appears only when the target looks like a typo of a known stage. Use \`ask\` only on live targets.
|
|
13054
|
+
For send, live session names, exact full session IDs, and unique 8-hex session UUID prefixes remain supported. \`send\` also takes a name glob (\`subagent-worker-*\`, or \`*\` for every session visible in your groups except you) and \`subagents:*\` (every running, released or paused subagent this session launched) or \`subagents:<runId>/*\` (those of one run); each recipient gets its own direct send, the result lists every recipient's outcome, a glob matching no session is an error naming close names, and patterns never reach outside your groups. Workflow-stage targets use \`workflow:<rootRunId>/<segment>[/<segment>...]\`; \`*\` matches one segment and \`**\` any depth. Use \`intercom list\` inside the invocation group to see live, pending, and possible future targets with queued counts. \`workflow:<rootRunId>/**\` reaches live stages now and remains sticky for every future stage until root termination; valid targets outside the known set still queue and settle undeliverable at terminal only if never delivered; a note appears only when the target looks like a typo of a known stage. Use \`ask\` only on live targets.
|
|
13055
|
+
${ASK_DESCRIPTION}
|
|
12438
13056
|
For send/ask/reply, Intercom retries recoverable disconnects internally up to three times with the same operation identity. Each new tool call is a new operation. If recovery ends with an unknown delivery outcome, do not repeat it automatically.
|
|
12439
13057
|
Usage:
|
|
12440
13058
|
intercom({ action: "list" }) → List sessions in your group
|
|
@@ -12442,25 +13060,29 @@ Usage:
|
|
|
12442
13060
|
intercom({ action: "join", group: "name" }) → Join or create a named group
|
|
12443
13061
|
intercom({ action: "leave" }) → Return to your resolved home group
|
|
12444
13062
|
intercom({ action: "send", to: "session-name", message: "..." }) → Send message (own group only)
|
|
12445
|
-
intercom({ action: "
|
|
13063
|
+
intercom({ action: "send", to: "subagent-worker-*", message: "..." }) → Send to every matching session
|
|
13064
|
+
intercom({ action: "send", to: "subagents:*", message: "..." }) → Send to every subagent you launched
|
|
13065
|
+
${ASK_USAGE}
|
|
12446
13066
|
intercom({ action: "reply", message: "..." }) → Reply to the active or exact pending ask
|
|
12447
|
-
intercom({ action: "pending" }) → List unresolved inbound asks
|
|
13067
|
+
intercom({ action: "pending" }) → List unresolved inbound asks and your pending asks
|
|
12448
13068
|
intercom({ action: "status" }) → Show connection status and your group
|
|
12449
13069
|
|
|
12450
13070
|
"default" is the shared group; "true" and "auto" are reserved for subagent auto-groups. Joining does not grant cross-group access; contact_supervisor remains the only cross-group path.`,
|
|
12451
|
-
promptSnippet:
|
|
12452
|
-
parameters:
|
|
12453
|
-
action:
|
|
12454
|
-
to:
|
|
12455
|
-
message:
|
|
12456
|
-
attachments:
|
|
12457
|
-
type:
|
|
12458
|
-
name:
|
|
12459
|
-
content:
|
|
12460
|
-
language:
|
|
13071
|
+
promptSnippet: `Use to coordinate with other local agent sessions in your intercom group. ${ASK_PROMPT_SNIPPET} Send/ask/reply retry reconnects internally; do not automatically repeat an unknown delivery outcome.`,
|
|
13072
|
+
parameters: Type4.Object({
|
|
13073
|
+
action: Type4.String({ description: "Action: 'list', 'join', 'leave', 'send', 'ask', 'reply', 'pending', 'cancel', or 'status'" }),
|
|
13074
|
+
to: Type4.Optional(Type4.String({ description: "Live session name, exact full session ID, unique 8-hex session UUID prefix, or `workflow:<rootRunId>/<segment>[/<segment>...]` path; `*` matches one segment and `**` any depth. Send also takes a session-name glob (`subagent-worker-*`, `*`) or `subagents:*` / `subagents:<runId>/*` for the subagents this session launched; ask needs one exact target. Send queues sticky pending/future delivery and `workflow:<rootRunId>/**` broadcasts to live and future stages; use `ask` only on live targets (for 'send', 'ask', or targeted 'reply')" })),
|
|
13075
|
+
message: Type4.Optional(Type4.String({ description: "Message to send (for 'send', 'ask', or 'reply' action)" })),
|
|
13076
|
+
attachments: Type4.Optional(Type4.Array(Type4.Object({
|
|
13077
|
+
type: Type4.Union([Type4.Literal("file"), Type4.Literal("snippet"), Type4.Literal("context")]),
|
|
13078
|
+
name: Type4.String(),
|
|
13079
|
+
content: Type4.String(),
|
|
13080
|
+
language: Type4.Optional(Type4.String())
|
|
12461
13081
|
}))),
|
|
12462
|
-
|
|
12463
|
-
|
|
13082
|
+
wait: Type4.Optional(askWaitSchema),
|
|
13083
|
+
askId: Type4.Optional(askIdSchema),
|
|
13084
|
+
replyTo: Type4.Optional(Type4.String({ description: "Exact pending-ask message ID or unique 8-hex UUID prefix; disambiguates concurrent asks, including asks from one sender" })),
|
|
13085
|
+
group: Type4.Optional(Type4.String({ description: "Group name for 'join'; read-only group filter for 'list'/'status'. 'send'/'ask' are locked to your own group." }))
|
|
12464
13086
|
}),
|
|
12465
13087
|
execute: (...args) => {
|
|
12466
13088
|
const invocationLease = activeLease;
|
|
@@ -12491,23 +13113,23 @@ Usage:
|
|
|
12491
13113
|
"Use contact_supervisor with reason='progress_update' only for meaningful progress or unexpected discoveries that change the plan.",
|
|
12492
13114
|
"Do not use contact_supervisor for routine completion handoffs; return the final subagent result normally."
|
|
12493
13115
|
],
|
|
12494
|
-
parameters:
|
|
12495
|
-
reason:
|
|
13116
|
+
parameters: Type4.Object({
|
|
13117
|
+
reason: Type4.String({
|
|
12496
13118
|
enum: ["need_decision", "progress_update", "interview_request"],
|
|
12497
13119
|
description: "Contact reason: 'need_decision' waits for a reply; 'interview_request' sends structured questions and waits for a reply; 'progress_update' sends a non-blocking update"
|
|
12498
13120
|
}),
|
|
12499
|
-
message:
|
|
13121
|
+
message: Type4.Optional(Type4.String({
|
|
12500
13122
|
description: "Decision request, optional interview note, or meaningful progress update for the supervisor"
|
|
12501
13123
|
})),
|
|
12502
|
-
interview:
|
|
12503
|
-
title:
|
|
12504
|
-
description:
|
|
12505
|
-
questions:
|
|
12506
|
-
id:
|
|
12507
|
-
type:
|
|
12508
|
-
question:
|
|
12509
|
-
options:
|
|
12510
|
-
context:
|
|
13124
|
+
interview: Type4.Optional(Type4.Object({
|
|
13125
|
+
title: Type4.Optional(Type4.String()),
|
|
13126
|
+
description: Type4.Optional(Type4.String()),
|
|
13127
|
+
questions: Type4.Array(Type4.Object({
|
|
13128
|
+
id: Type4.String(),
|
|
13129
|
+
type: Type4.String({ description: "Question type: single, multi, text, image, or info" }),
|
|
13130
|
+
question: Type4.String(),
|
|
13131
|
+
options: Type4.Optional(Type4.Array(Type4.Unknown())),
|
|
13132
|
+
context: Type4.Optional(Type4.String())
|
|
12511
13133
|
}))
|
|
12512
13134
|
}, { description: "Structured interview request for reason='interview_request'" }))
|
|
12513
13135
|
}),
|