@agimon-ai/po-team 0.0.0-alpha.219 → 0.0.0-alpha.220

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.
@@ -6,7 +6,7 @@ const require_agentDiscovery = require("../agentDiscovery-D0VcSETk.cjs");
6
6
  const require_environment = require("../environment-COaoVl5M.cjs");
7
7
  const require_capabilityCeiling = require("../capabilityCeiling-x2WmB2TL.cjs");
8
8
  const require_subagentPolicy = require("../subagentPolicy-DYj_SOTG.cjs");
9
- const require_subagentTool = require("../subagentTool-CqXgI3iD.cjs");
9
+ const require_subagentTool = require("../subagentTool-CXBB6f9e.cjs");
10
10
  const require_teamSnapshot = require("../teamSnapshot-oKuGFdYc.cjs");
11
11
  let _agimon_ai_po_core_childProcess = require("@agimon-ai/po-core/childProcess");
12
12
  let _agimon_ai_po_session = require("@agimon-ai/po-session");
@@ -143,9 +143,8 @@ function terminalState(event) {
143
143
  function entryKey(sessionId, runId) {
144
144
  return JSON.stringify([sessionId, runId]);
145
145
  }
146
- /** A stored run's identity, as `start` put it in the request's `meta`. */
147
- function storedRunIdentity(run) {
148
- const meta = run.request.meta;
146
+ /** A run's identity from the `meta` that `start` stored with its request. */
147
+ function parseRunIdentity(meta) {
149
148
  if (typeof meta?.identity !== "string") return void 0;
150
149
  return {
151
150
  identity: meta.identity,
@@ -153,9 +152,20 @@ function storedRunIdentity(run) {
153
152
  ...meta.awaited === true ? { awaited: true } : {},
154
153
  ...meta.delivery === "silent" ? { delivery: "silent" } : {},
155
154
  ...typeof meta.agentDescription === "string" ? { agentDescription: meta.agentDescription } : {},
156
- ...typeof meta.agentFilePath === "string" ? { agentFilePath: meta.agentFilePath } : {}
155
+ ...typeof meta.agentFilePath === "string" ? { agentFilePath: meta.agentFilePath } : {},
156
+ ...isTeamTask(meta.teamTask) ? { teamTask: {
157
+ id: meta.teamTask.id,
158
+ subject: meta.teamTask.subject
159
+ } } : {}
157
160
  };
158
161
  }
162
+ function isTeamTask(value) {
163
+ return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.subject === "string";
164
+ }
165
+ /** A stored run's identity, as `start` put it in the request's `meta`. */
166
+ function storedRunIdentity(run) {
167
+ return parseRunIdentity(run.request.meta);
168
+ }
159
169
  var NativeRunCoordinator = class {
160
170
  childSessions;
161
171
  tracker;
@@ -335,6 +345,10 @@ var NativeRunCoordinator = class {
335
345
  async reported(runId) {
336
346
  return this.service().reported?.(runId);
337
347
  }
348
+ /** Whether this host can give a finished run new input on its own conversation. */
349
+ canResume() {
350
+ return !this.closed && typeof this.childSessions?.get()?.resume === "function";
351
+ }
338
352
  async steer(sessionId, runId, message, signal) {
339
353
  const handle = this.get(sessionId, runId);
340
354
  if (!handle) throw new Error(`No active native run matches '${runId}'.`);
@@ -406,6 +420,7 @@ var NativeRunCoordinator = class {
406
420
  identity: entry.identity.identity,
407
421
  inline: entry.identity.inline
408
422
  } : {},
423
+ ...entry.identity?.teamTask ? { teamTask: entry.identity.teamTask } : {},
409
424
  task: entry.request.task,
410
425
  cwd: entry.request.cwd,
411
426
  runtime: "pi",
@@ -1337,9 +1352,14 @@ function deadlineWarning(timeoutMs) {
1337
1352
  text: `This delegation will time out in about ${seconds} second${seconds === 1 ? "" : "s"}. Stop exploring now, complete the highest-value remaining work, and return a concise result before the deadline. If you cannot finish, return verified findings and blockers immediately.`
1338
1353
  };
1339
1354
  }
1355
+ function continueHint(runId, kind) {
1356
+ if (!kind.canResume) return "This host cannot resume finished runs: start a new run and pass it the work so far below in its task.";
1357
+ if (kind.mode === "awaited") return `Continue this run instead of starting a new one: team.run({ resumeRunId: "${runId}", task: "<next step>" }) resumes it with everything it already did.`;
1358
+ return `Continue this run instead of starting a new one: team.steer({ id: "${runId}", message: "<next step>" }) resumes it with everything it already did (without code mode: subagent({"action":"steer","id":"${runId}","message":"<next step>"})).`;
1359
+ }
1340
1360
  /** What a launcher reports for a run stopped at its deadline: how to continue it, and its transcript tail. */
1341
- function timedOutResult(runId, timeoutMs, entries) {
1342
- const error = `Timed out after ${timeoutMs}ms. Continue this run instead of starting a new one: subagent({"action":"steer","id":"${runId}","message":"<next step>"}) resumes it with everything it already did.`;
1361
+ function timedOutResult(runId, timeoutMs, entries, kind) {
1362
+ const error = `Timed out after ${timeoutMs}ms. ${continueHint(runId, kind)}`;
1343
1363
  if (!entries?.length) return { error };
1344
1364
  return {
1345
1365
  error,
@@ -1350,14 +1370,23 @@ function timedOutResult(runId, timeoutMs, entries) {
1350
1370
  //#region src/services/awaitedInlineRun/index.ts
1351
1371
  const DEFAULT_TIMEOUT_MS$1 = 18e5;
1352
1372
  const MAX_TIMEOUT_MS = 72e5;
1373
+ const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
1374
+ "completed",
1375
+ "failed",
1376
+ "stopped"
1377
+ ]);
1353
1378
  function validate(input) {
1354
1379
  if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("team.run requires an object.");
1355
1380
  const value = input;
1356
- for (const key of ["systemPrompt", "task"]) if (typeof value[key] !== "string" || !value[key].trim()) throw new Error(`team.run requires a nonblank ${key}.`);
1381
+ const resuming = value.resumeRunId !== void 0;
1382
+ if (resuming && (typeof value.resumeRunId !== "string" || !value.resumeRunId.trim())) throw new Error("team.run resumeRunId must be a nonblank run ID.");
1383
+ if (resuming && (value.systemPrompt !== void 0 || value.model !== void 0)) throw new Error("team.run resumeRunId continues a run with its own prompt and model: pass only resumeRunId, task and timeoutMs.");
1384
+ for (const key of resuming ? ["task"] : ["systemPrompt", "task"]) if (typeof value[key] !== "string" || !value[key].trim()) throw new Error(`team.run requires a nonblank ${key}.`);
1357
1385
  if (value.model !== void 0 && (typeof value.model !== "string" || !value.model.trim())) throw new Error("team.run model must be a nonblank string.");
1358
1386
  if (value.timeoutMs !== void 0 && (typeof value.timeoutMs !== "number" || !Number.isSafeInteger(value.timeoutMs) || value.timeoutMs <= 0 || value.timeoutMs > MAX_TIMEOUT_MS)) throw new Error(`team.run timeoutMs must be an integer from 1 to ${MAX_TIMEOUT_MS}.`);
1359
1387
  return {
1360
- systemPrompt: value.systemPrompt.trim(),
1388
+ ...resuming ? { resumeRunId: value.resumeRunId.trim() } : {},
1389
+ ...typeof value.systemPrompt === "string" ? { systemPrompt: value.systemPrompt.trim() } : {},
1361
1390
  task: value.task.trim(),
1362
1391
  ...typeof value.model === "string" ? { model: value.model.trim() } : {},
1363
1392
  ...typeof value.timeoutMs === "number" ? { timeoutMs: value.timeoutMs } : {}
@@ -1395,6 +1424,40 @@ function createAwaitedInlineRunner(options) {
1395
1424
  return;
1396
1425
  }
1397
1426
  };
1427
+ /** Continues the finished awaited run the caller named, or throws why it cannot; never starts a fresh run. */
1428
+ const resumeNamed = async (runId, task) => {
1429
+ const { coordinator, execution } = options;
1430
+ if (!coordinator.canResume()) throw new Error("This host cannot resume finished runs; start a new team.run.");
1431
+ const status = coordinator.status(execution.sessionId, runId);
1432
+ if (status && !TERMINAL_STATUSES.has(status.status)) throw new Error(`Run '${runId}' is still running; wait for its result before resuming it.`);
1433
+ const reported = await coordinator.reported(runId);
1434
+ if (!reported) throw new Error(`No finished team.run matches '${runId}'; start a new team.run.`);
1435
+ const identity = parseRunIdentity(reported.meta);
1436
+ if (!identity) throw new Error(`Run '${runId}' is no longer kept for resume; start a new team.run with the work so far.`);
1437
+ if (!identity.awaited) throw new Error(`Run '${runId}' is a background run: continue it with team.steer({ id: "${runId}", message: "<next step>" }).`);
1438
+ const waiter = coordinator.waitFor(execution.sessionId, runId);
1439
+ try {
1440
+ await coordinator.resume(execution.sessionId, createSessionScope(execution.sessionId), {
1441
+ runId,
1442
+ agent: reported.agent ?? status?.agent ?? "inline",
1443
+ task,
1444
+ cwd: execution.cwd
1445
+ }, {
1446
+ text: task,
1447
+ sender: MAIN_AGENT_SENDER
1448
+ }, {
1449
+ identity: identity.identity,
1450
+ inline: true,
1451
+ awaited: true,
1452
+ delivery: "silent"
1453
+ });
1454
+ return waiter;
1455
+ } catch (error) {
1456
+ waiter.dispose();
1457
+ const reason = error instanceof Error ? error.message : String(error);
1458
+ throw new Error(`Run '${runId}' could not resume: ${reason} Start a new team.run with the work so far.`);
1459
+ }
1460
+ };
1398
1461
  const execute = async (input, parentSignal) => {
1399
1462
  let runId;
1400
1463
  let promptHash;
@@ -1435,13 +1498,19 @@ function createAwaitedInlineRunner(options) {
1435
1498
  const execution = options.execution;
1436
1499
  const models = await availableModelInfos(execution);
1437
1500
  signal.throwIfAborted();
1438
- promptHash = (0, node_crypto.createHash)("sha256").update(JSON.stringify([
1439
- params.systemPrompt,
1440
- params.task,
1441
- params.model ?? null
1442
- ])).digest("hex");
1443
- const previous = options.previousRun?.(execution.sessionId, promptHash);
1444
- waiter = previous === void 0 ? void 0 : await resumeRun(previous, params.task);
1501
+ let previous;
1502
+ if (params.resumeRunId !== void 0) {
1503
+ previous = params.resumeRunId;
1504
+ waiter = await resumeNamed(previous, params.task);
1505
+ } else {
1506
+ promptHash = (0, node_crypto.createHash)("sha256").update(JSON.stringify([
1507
+ params.systemPrompt,
1508
+ params.task,
1509
+ params.model ?? null
1510
+ ])).digest("hex");
1511
+ previous = options.previousRun?.(execution.sessionId, promptHash);
1512
+ waiter = previous === void 0 ? void 0 : await resumeRun(previous, params.task);
1513
+ }
1445
1514
  if (previous !== void 0 && waiter) {
1446
1515
  runId = previous;
1447
1516
  notify("running");
@@ -1496,7 +1565,10 @@ function createAwaitedInlineRunner(options) {
1496
1565
  error: reason
1497
1566
  });
1498
1567
  const entries = await options.coordinator.readTranscript(execution.sessionId, runId, 40).catch(() => void 0);
1499
- const timedOut = timedOutResult(runId, timeoutMs, entries);
1568
+ const timedOut = timedOutResult(runId, timeoutMs, entries, {
1569
+ mode: "awaited",
1570
+ canResume: options.coordinator.canResume()
1571
+ });
1500
1572
  return finish({
1501
1573
  ...stopped,
1502
1574
  status: "stopped",
@@ -2964,7 +3036,8 @@ var SpawnPlanner = class {
2964
3036
  delivery: "silent"
2965
3037
  } : silent ? { delivery: "silent" } : {},
2966
3038
  ...agentConfig.description ? { agentDescription: agentConfig.description } : {},
2967
- ...agentConfig.filePath ? { agentFilePath: agentConfig.filePath } : {}
3039
+ ...agentConfig.filePath ? { agentFilePath: agentConfig.filePath } : {},
3040
+ ...taskInput.teamTask ? { teamTask: { ...taskInput.teamTask } } : {}
2968
3041
  }, signal);
2969
3042
  } catch (error) {
2970
3043
  intercom?.dispose?.();
@@ -3243,7 +3316,10 @@ function createDelegationBridge(deps) {
3243
3316
  if (entry.settled) return;
3244
3317
  const entries = await deps.readTranscript?.(sessionId, runId, 40).catch(() => void 0);
3245
3318
  if (entry.settled) return;
3246
- const timedOut = timedOutResult(runId, timeoutMs, entries);
3319
+ const timedOut = timedOutResult(runId, timeoutMs, entries, {
3320
+ mode: "background",
3321
+ canResume: deps.canResume?.() ?? false
3322
+ });
3247
3323
  finish(entry, {
3248
3324
  requestId: entry.requestId,
3249
3325
  runId,
@@ -3283,7 +3359,8 @@ function createDelegationBridge(deps) {
3283
3359
  ...status?.summary ? { output: status.summary } : {},
3284
3360
  ...status?.error ? { error: status.error } : {},
3285
3361
  ...status?.sessionFile ? { sessionFile: status.sessionFile } : {},
3286
- durationMs: status?.endedAt && status.startedAt ? Math.max(0, status.endedAt - status.startedAt) : wait.elapsedMs
3362
+ durationMs: status?.endedAt && status.startedAt ? Math.max(0, status.endedAt - status.startedAt) : wait.elapsedMs,
3363
+ ...completed && !request.internal ? { announced: true } : {}
3287
3364
  }, ctx);
3288
3365
  };
3289
3366
  const onRequested = async (request, ctx, session) => {
@@ -3305,7 +3382,8 @@ function createDelegationBridge(deps) {
3305
3382
  ...request.inlineAgent ? { inlineAgent: request.inlineAgent } : {},
3306
3383
  task: request.prompt,
3307
3384
  model: request.model,
3308
- ...request.context ? { context: request.context } : {}
3385
+ ...request.context ? { context: request.context } : {},
3386
+ ...request.teamTask ? { teamTask: request.teamTask } : {}
3309
3387
  },
3310
3388
  cwd: request.cwd,
3311
3389
  agentScope: "both",
@@ -3513,6 +3591,10 @@ const FANOUT_SUFFIX_SEPARATOR = "-";
3513
3591
  const MAX_MESSAGE_BYTES = 65536;
3514
3592
  /** An unanswered ask wakes its asker once, after this long. */
3515
3593
  const ASK_WAKE_MS = 18e4;
3594
+ /** Per sender and recipient: messages (asks included) and asks allowed in any window. Replies and retries are free. */
3595
+ const INTERCOM_WINDOW_MS = 6e5;
3596
+ const INTERCOM_MESSAGE_LIMIT = 6;
3597
+ const INTERCOM_ASK_LIMIT = 2;
3516
3598
  const MAX_IDEMPOTENCY_KEYS = 1024;
3517
3599
  const HASH_ALGORITHM$1 = "sha256";
3518
3600
  const TOKEN_BYTES = 32;
@@ -3634,12 +3716,23 @@ function formatDirectMessage(from, kind, requestId, message) {
3634
3716
  }
3635
3717
  var NativeTeamDirectChannel = class {
3636
3718
  root;
3719
+ observe;
3637
3720
  members = /* @__PURE__ */ new Map();
3638
3721
  asks = /* @__PURE__ */ new Map();
3639
3722
  delivered = new BoundedKeySet(MAX_IDEMPOTENCY_KEYS);
3723
+ /** Recent sends per sender and recipient, for the intercom budget. */
3724
+ sends = /* @__PURE__ */ new Map();
3640
3725
  disposed = false;
3641
- constructor(root) {
3726
+ constructor(root, observe) {
3642
3727
  this.root = root;
3728
+ this.observe = observe;
3729
+ }
3730
+ record(member, kind, outcome) {
3731
+ this.observe?.("po_team.intercom_sent", {
3732
+ kind,
3733
+ outcome,
3734
+ "team.role": member.context.role
3735
+ });
3643
3736
  }
3644
3737
  bindMain(context, transport) {
3645
3738
  this.members.set(context.memberId, {
@@ -3797,6 +3890,7 @@ var NativeTeamDirectChannel = class {
3797
3890
  if (!request || request.toMemberId !== memberId || !asker) throw new PoTeamExpectedError("recipient_not_found", `No open intercom ask matches requestId '${params.requestId}'. It may already be answered, or its asker has finished.`, false, "Call intercom({\"action\":\"pending\"}) and retry with an exact requestId, or continue without replying.");
3798
3891
  await this.deliver(asker, formatDirectMessage(member.context, "reply", request.id, message));
3799
3892
  this.closeAsk(request);
3893
+ this.record(member, "reply", "delivered");
3800
3894
  return {
3801
3895
  content: [{
3802
3896
  type: "text",
@@ -3810,7 +3904,7 @@ var NativeTeamDirectChannel = class {
3810
3904
  };
3811
3905
  }
3812
3906
  const target = this.findMember(params.to);
3813
- if (!target) throw new PoTeamExpectedError("recipient_not_found", `Active intercom member '${params.to}' was not found.`, true, "Call intercom({\"action\":\"members\"}) and retry with an active member id.");
3907
+ if (!target) throw new PoTeamExpectedError("recipient_not_found", `Active intercom member '${params.to}' was not found.`, true, member.context.role === "main" ? "Call team.members() and retry with an active member id. If the teammate has finished, give it follow-up work with team.steer({ id, message }). Without code mode use intercom({\"action\":\"members\"}) and subagent({\"action\":\"steer\"})." : "Call intercom({\"action\":\"members\"}) and retry with an active member id. If the teammate has already finished, it cannot receive messages; include it in your final answer for main.");
3814
3908
  const messageId = operationMessageId(memberId, operationId);
3815
3909
  const isAsk = params.action === "ask";
3816
3910
  const result = () => ({
@@ -3828,6 +3922,13 @@ var NativeTeamDirectChannel = class {
3828
3922
  }
3829
3923
  });
3830
3924
  if (this.delivered.has(messageId) || this.asks.has(messageId)) return result();
3925
+ const budgetKey = JSON.stringify([memberId, target.context.memberId]);
3926
+ const now = Date.now();
3927
+ const recent = (this.sends.get(budgetKey) ?? []).filter((send) => now - send.at < INTERCOM_WINDOW_MS);
3928
+ if (isAsk && recent.filter((send) => send.ask).length >= INTERCOM_ASK_LIMIT || recent.length >= INTERCOM_MESSAGE_LIMIT) {
3929
+ this.record(member, params.action, "rate_limited");
3930
+ throw new PoTeamExpectedError("rate_limited", `Intercom budget to '${target.context.memberId}' is spent: ${INTERCOM_MESSAGE_LIMIT} messages and ${INTERCOM_ASK_LIMIT} asks per recipient in any 10 minutes.`, true, member.context.role === "main" ? "Wait for its result or pending questions, fold your points into one later message, or answer open asks with reply, which is free." : "Stop messaging and keep working; put what you would have sent in your final result for the main agent. Replies to open asks are still free.");
3931
+ }
3831
3932
  const ask = isAsk ? this.openAsk(memberId, target.context.memberId, messageId) : void 0;
3832
3933
  try {
3833
3934
  await this.deliver(target, formatDirectMessage(member.context, params.action, messageId, message));
@@ -3836,6 +3937,11 @@ var NativeTeamDirectChannel = class {
3836
3937
  throw error;
3837
3938
  }
3838
3939
  this.delivered.add(messageId);
3940
+ this.sends.set(budgetKey, [...recent, {
3941
+ at: now,
3942
+ ask: isAsk
3943
+ }]);
3944
+ this.record(member, params.action, "delivered");
3839
3945
  return result();
3840
3946
  }
3841
3947
  /** Stored before delivery so a reply that races the delivery still finds it. */
@@ -3877,7 +3983,12 @@ var NativeTeamDirectChannel = class {
3877
3983
  if (!query) return void 0;
3878
3984
  const lowered = query.toLowerCase();
3879
3985
  const normalized = normalizeTeamMemberName(query);
3880
- return [...this.members.values()].find((member) => member.context.memberId === query || member.context.memberId === normalized || member.context.agent?.toLowerCase() === lowered || member.context.runId?.toLowerCase() === lowered);
3986
+ const members = [...this.members.values()];
3987
+ const exact = members.find((member) => member.context.memberId === query || member.context.memberId === normalized || member.context.runId?.toLowerCase() === lowered);
3988
+ if (exact) return exact;
3989
+ const byAgent = members.filter((member) => member.context.agent?.toLowerCase() === lowered);
3990
+ if (byAgent.length > 1) throw new PoTeamExpectedError("recipient_ambiguous", `Several intercom members run agent '${query}': ${byAgent.map((member) => member.context.memberId).join(", ")}.`, true, "Retry with one exact member id from that list.");
3991
+ return byAgent[0];
3881
3992
  }
3882
3993
  async deliver(target, message) {
3883
3994
  const id = target.context.memberId;
@@ -3948,12 +4059,16 @@ function ensureNativeTeamRoot(rootSessionId) {
3948
4059
  };
3949
4060
  }
3950
4061
  var NativeTeamChannelService = class {
4062
+ observe;
3951
4063
  runtimes = /* @__PURE__ */ new WeakMap();
3952
4064
  directChannels = /* @__PURE__ */ new Map();
4065
+ constructor(observe) {
4066
+ this.observe = observe;
4067
+ }
3953
4068
  directChannelForRoot(rootSessionId) {
3954
4069
  const existing = this.directChannels.get(rootSessionId);
3955
4070
  if (existing) return existing;
3956
- const channel = new NativeTeamDirectChannel(ensureNativeTeamRoot(rootSessionId));
4071
+ const channel = new NativeTeamDirectChannel(ensureNativeTeamRoot(rootSessionId), this.observe);
3957
4072
  this.directChannels.set(rootSessionId, channel);
3958
4073
  return channel;
3959
4074
  }
@@ -4493,7 +4608,8 @@ var SubagentToolService = class {
4493
4608
  ...request.inlineAgent ? { inlineAgent: request.inlineAgent } : {},
4494
4609
  task: request.task.trim(),
4495
4610
  ...request.cwd ? { cwd: request.cwd } : {},
4496
- ...request.model ? { model: request.model } : {}
4611
+ ...request.model ? { model: request.model } : {},
4612
+ ...request.context ? { context: request.context } : {}
4497
4613
  };
4498
4614
  });
4499
4615
  const parentForkSource = await captureSessionForkSource(ctx.sessionManager, "tool", this.io);
@@ -4695,7 +4811,8 @@ function createHeadlessSubagentTool(runtime, initialExecution, config) {
4695
4811
  task: request.task.trim(),
4696
4812
  ...request.inlineAgent ? { inlineAgent: request.inlineAgent } : {},
4697
4813
  ...request.cwd ? { cwd: request.cwd } : {},
4698
- ...request.model ? { model: request.model } : {}
4814
+ ...request.model ? { model: request.model } : {},
4815
+ ...request.context ? { context: request.context } : {}
4699
4816
  })),
4700
4817
  cwd: execution.cwd,
4701
4818
  agentScope: scopeOf(params.scope),
@@ -4970,9 +5087,9 @@ const GROUPED_SUCCESS_ACTION = "Handle each result now: incorporate it, reject i
4970
5087
  */
4971
5088
  function completionAction(details) {
4972
5089
  const hasPreview = details.resultPreview.trim().length > 0;
4973
- const transcriptRequest = `{ action: "status", id: "${details.runId}", transcriptLines: ${RECENT_TRANSCRIPT_LINES} }`;
5090
+ const transcriptRequest = `team.status({ id: "${details.runId}", transcriptLines: ${RECENT_TRANSCRIPT_LINES} }) (the subagent tool's status action without code mode)`;
4974
5091
  if (details.status === "completed") return hasPreview ? SINGLE_SUCCESS_ACTION : `No summary was produced. Inspect recent output with ${transcriptRequest} before handling this result.`;
4975
- if (details.status === "paused") return `Run is paused. Inspect it with { action: "status", id: "${details.runId}" }, then restore it only if status reports it as resumable.`;
5092
+ if (details.status === "paused") return `Run is paused. Inspect it with team.status({ id: "${details.runId}" }) (the subagent tool's status action without code mode), then restore it only if status reports it as resumable.`;
4976
5093
  return hasPreview ? `Use the failure summary first. If it does not explain the failure, inspect recent output with ${transcriptRequest}.` : `No failure summary was produced. Inspect recent output with ${transcriptRequest}.`;
4977
5094
  }
4978
5095
  function formatSessionLine(details) {
@@ -5075,7 +5192,10 @@ function buildCompletionDetails(result) {
5075
5192
  const status = success === false && (state === "paused" || summary.startsWith("Paused after interrupt.")) ? "paused" : success === false ? "failed" : "completed";
5076
5193
  const taskIndex = asNumber(result.taskIndex);
5077
5194
  const totalTasks = asNumber(result.totalTasks);
5078
- const taskInfo = taskIndex !== void 0 && totalTasks !== void 0 ? ` (${taskIndex + 1}/${totalTasks})` : void 0;
5195
+ const indexInfo = taskIndex !== void 0 && totalTasks !== void 0 ? ` (${taskIndex + 1}/${totalTasks})` : "";
5196
+ const teamTask = typeof result.teamTask === "object" && result.teamTask !== null ? result.teamTask : void 0;
5197
+ const teamTaskId = asString(teamTask?.id);
5198
+ const taskInfo = indexInfo + (teamTaskId ? ` (task #${teamTaskId}: ${asString(teamTask?.subject) ?? ""})` : "") || void 0;
5079
5199
  const handoffPath = asString((typeof result.parallelHandoff === "object" && result.parallelHandoff !== null ? result.parallelHandoff : void 0)?.path);
5080
5200
  const shareUrl = asString(result.shareUrl);
5081
5201
  const shareError = asString(result.shareError);
@@ -6027,6 +6147,7 @@ function createTeamConfigNamespace(options) {
6027
6147
  const t = options.translate ?? ((_key, fallback, vars) => (0, _agimon_ai_po_core_locale.formatMessage)(fallback, vars));
6028
6148
  return {
6029
6149
  name: "teamConfig",
6150
+ guide: "help-how-to-team",
6030
6151
  summary: "Help mode only: list, read, save and remove Team agent files, and read or set Team defaults and per-agent models in host or workspace config.yaml, or draft Global YAML. The person approves every write. Load help-how-to-team first.",
6031
6152
  portable: true,
6032
6153
  declarations: DECLARATIONS$1,
@@ -6088,15 +6209,12 @@ interface TeamRun {
6088
6209
  status: string | undefined;
6089
6210
  startedAt?: number;
6090
6211
  updatedAt?: number;
6091
- activityState?: 'starting' | 'working' | 'tool' | 'waiting_for_reply' | 'needs_attention' | 'finalizing' | 'active_long_running';
6092
- attentionReason?: string;
6093
6212
  runtime?: string;
6094
6213
  native?: boolean;
6095
6214
  summary?: string;
6096
6215
  error?: string;
6097
6216
  tokens?: number;
6098
6217
  cost?: number;
6099
- currentTool?: string;
6100
6218
  toolCount?: number;
6101
6219
  }
6102
6220
  /** The text the direct tool would show, plus its structured details. */
@@ -6110,8 +6228,12 @@ declare const team: {
6110
6228
  members(): TeamMember[];
6111
6229
  /** Tracked runs. Finished runs drop off 10 minutes after acknowledgement. */
6112
6230
  runs(): TeamRun[];
6113
- /** Await one inline agent. Inherits capabilities except delegation and parent-bound code mode. Never rejects. */
6114
- run(input: { systemPrompt: string; task: string; model?: string; timeoutMs?: number }): Promise<{
6231
+ /**
6232
+ * Await one inline agent. Inherits capabilities except delegation and parent-bound code mode. Never rejects.
6233
+ * Pass resumeRunId (and no systemPrompt) to continue a finished team.run on its own conversation, such as after a
6234
+ * timeout or for a quick re-check; start a new run for an unbiased second opinion. Main agent only.
6235
+ */
6236
+ run(input: { systemPrompt?: string; task: string; resumeRunId?: string; model?: string; timeoutMs?: number }): Promise<{
6115
6237
  runId?: string; status: 'completed' | 'failed' | 'stopped'; output: string; error?: string;
6116
6238
  }>;
6117
6239
  /** Compatibility forwarder, main-agent coordinators only. Prefer sessions.start. */
@@ -6120,7 +6242,8 @@ declare const team: {
6120
6242
  agents(input?: { name?: string; cwd?: string; scope?: AgentScope }): Promise<TeamToolResult>;
6121
6243
  /** Start persistent background runs. Each completion arrives later as a message: end the turn rather than polling. */
6122
6244
  start(input: {
6123
- requests: { agent: string; task: string; inlineAgent?: { systemPrompt: string; tools?: string[] }; cwd?: string; model?: string }[];
6245
+ /** context: 'fresh' (default) starts clean; 'fork' copies this conversation so the child knows what you know. */
6246
+ requests: { agent: string; task: string; inlineAgent?: { systemPrompt: string; tools?: string[] }; cwd?: string; model?: string; context?: 'fresh' | 'fork' }[];
6124
6247
  concurrency?: number;
6125
6248
  artifacts?: boolean;
6126
6249
  scope?: AgentScope;
@@ -6189,15 +6312,12 @@ function createTeamNamespace(options) {
6189
6312
  status: job.status,
6190
6313
  startedAt: job.startedAt,
6191
6314
  updatedAt: job.updatedAt,
6192
- activityState: job.activityState,
6193
- attentionReason: job.attentionReason,
6194
6315
  runtime: job.runtime,
6195
6316
  native: job.native,
6196
6317
  summary: job.summary,
6197
6318
  error: job.error,
6198
6319
  tokens: job.tokens,
6199
6320
  cost: job.cost,
6200
- currentTool: job.currentTool,
6201
6321
  toolCount: job.toolCount
6202
6322
  }));
6203
6323
  const snapshot = JSON.parse(JSON.stringify(runs));
@@ -6207,6 +6327,7 @@ function createTeamNamespace(options) {
6207
6327
  members.run = (input) => {
6208
6328
  const pending = (async () => {
6209
6329
  try {
6330
+ if (run.caller !== "main") throw new Error("team.run is for the main agent only. Report your result to the main agent instead.");
6210
6331
  check();
6211
6332
  if (!options.run) throw new Error("Awaited inline agents are unavailable on this host.");
6212
6333
  return JSON.parse(JSON.stringify(await options.run(input, signal)));
@@ -6273,7 +6394,7 @@ function formatCoordinatorPeers(scope, peers) {
6273
6394
  "Questions about progress, status or what is going on mean these sessions, not only this chat: message them for what you need, then report from their replies as they arrive."
6274
6395
  ];
6275
6396
  const hidden = ordered.length - shown.length;
6276
- if (hidden > 0) lines.push(`${String(hidden)} more not shown: use network.list() to list every session, or intercom members without code mode.`);
6397
+ if (hidden > 0) lines.push(`${String(hidden)} more not shown: use network.list() to list every session.`);
6277
6398
  return lines;
6278
6399
  }
6279
6400
  /**
@@ -6296,7 +6417,7 @@ function teamRosterNote(roster) {
6296
6417
  return [
6297
6418
  "<system-reminder>",
6298
6419
  roster || "You are in no session group and have no active subagents now.",
6299
- "This replaces any earlier roster note. Use intercom members for live status.",
6420
+ "This replaces any earlier roster note. For live status use team.members() and team.runs() in code mode, or intercom members without it.",
6300
6421
  "</system-reminder>"
6301
6422
  ].join("\n");
6302
6423
  }
@@ -6386,12 +6507,14 @@ var ManagementActions = class {
6386
6507
  nativeRuns;
6387
6508
  externalProcesses;
6388
6509
  teamChannel;
6510
+ observe;
6389
6511
  scope;
6390
- constructor(jobs, nativeRuns, externalProcesses, teamChannel) {
6512
+ constructor(jobs, nativeRuns, externalProcesses, teamChannel, observe) {
6391
6513
  this.jobs = jobs;
6392
6514
  this.nativeRuns = nativeRuns;
6393
6515
  this.externalProcesses = externalProcesses;
6394
6516
  this.teamChannel = teamChannel;
6517
+ this.observe = observe;
6395
6518
  }
6396
6519
  bindSessionScope(scope) {
6397
6520
  if (this.scope && this.scope.scopeKey !== scope.scopeKey) throw new Error("Team management scope is immutable for the active session runtime.");
@@ -6418,7 +6541,7 @@ var ManagementActions = class {
6418
6541
  }
6419
6542
  requireActiveJob(id) {
6420
6543
  const job = this.resolveJob(id);
6421
- if (!job) throw new PoTeamExpectedError("run_not_found", `No active run matches '${id}'.`, false, "Call subagent({\"action\":\"status\"}) and retry with an exact run id.");
6544
+ if (!job) throw new PoTeamExpectedError("run_not_found", `No active run matches '${id}'.`, false, "Call team.runs() in code mode, or subagent({\"action\":\"status\"}) without it, and retry with an exact run id.");
6422
6545
  return job;
6423
6546
  }
6424
6547
  status(id) {
@@ -6477,13 +6600,19 @@ var ManagementActions = class {
6477
6600
  const scope = this.requireScope();
6478
6601
  const job = this.resolveJob(id) ?? await this.reportedJob(id) ?? this.requireActiveJob(id);
6479
6602
  const finished = job.status !== void 0 && TERMINAL_ASYNC_JOB_STATES.has(job.status);
6480
- if (!job.native || !finished || !this.nativeRuns?.resume || this.nativeRuns.get(scope.rootSessionId, job.runId)) return this.steer(job.runId, message, void 0, signal);
6481
- await this.resume(scope, job, message);
6603
+ if (!job.native || !finished || !this.nativeRuns?.resume || this.nativeRuns.get(scope.rootSessionId, job.runId)) {
6604
+ const steered = await this.steer(job.runId, message, void 0, signal);
6605
+ this.observe?.("po_team.steer", { outcome: steered.state });
6606
+ return steered;
6607
+ }
6608
+ const teamTask = await this.resume(scope, job, message);
6609
+ this.observe?.("po_team.steer", { outcome: "resumed" });
6610
+ const reminder = teamTask ? ` It still works on task #${teamTask.id} (${teamTask.subject}); update that task.` : "";
6482
6611
  return {
6483
6612
  requestId: (0, node_crypto.randomUUID)(),
6484
6613
  index: 0,
6485
6614
  state: "resumed",
6486
- message: "The finished run continues on its own conversation; its completion arrives like a new run."
6615
+ message: `The finished run continues on its own conversation; its completion arrives like a new run.${reminder}`
6487
6616
  };
6488
6617
  }
6489
6618
  async steer(id, message, targetIndex, signal) {
@@ -6536,12 +6665,14 @@ var ManagementActions = class {
6536
6665
  async resume(scope, job, message) {
6537
6666
  const agent = job.agent ?? "subagent";
6538
6667
  const task = job.task ?? (typeof message === "string" ? message : message.text);
6668
+ const teamTask = parseRunIdentity((await this.nativeRuns?.reported?.(job.runId))?.meta)?.teamTask;
6539
6669
  const projection = this.nativeRuns?.status(scope.rootSessionId, job.runId);
6540
6670
  const identity = job.identity ? {
6541
6671
  identity: job.identity,
6542
6672
  inline: job.inline ?? false,
6543
6673
  ...projection?.agentDescription ? { agentDescription: projection.agentDescription } : {},
6544
- ...projection?.agentFilePath ? { agentFilePath: projection.agentFilePath } : {}
6674
+ ...projection?.agentFilePath ? { agentFilePath: projection.agentFilePath } : {},
6675
+ ...teamTask ? { teamTask } : {}
6545
6676
  } : void 0;
6546
6677
  const intercom = this.teamChannel?.createNativeChildIntercom({
6547
6678
  rootSessionId: scope.rootSessionId,
@@ -6567,6 +6698,7 @@ var ManagementActions = class {
6567
6698
  intercom?.dispose?.();
6568
6699
  throw error;
6569
6700
  }
6701
+ return teamTask;
6570
6702
  }
6571
6703
  };
6572
6704
  //#endregion
@@ -6926,9 +7058,9 @@ function createTeamExtensionRuntime(reportConcurrencyEvent, options) {
6926
7058
  const mcpToolResolver = new McpDirectToolResolverBinding();
6927
7059
  const completionNotifier = new CompletionNotifier();
6928
7060
  const nativeRuns = new NativeRunCoordinator(options.childSessions, asyncJobTracker, completionNotifier, options.nativeRunProjection);
6929
- const teamChannel = new NativeTeamChannelService();
7061
+ const teamChannel = new NativeTeamChannelService(options.observe);
6930
7062
  const spawnPlanner = new SpawnPlanner(options.discoveryIo, discovery, asyncSubagentSpawner, capabilityPolicies, skills, report, mcpToolResolver, admission, options.childSessions, nativeRuns, teamChannel, options.environment, options.agentConfig);
6931
- const management = new ManagementActions(asyncJobTracker, nativeRuns, void 0, teamChannel);
7063
+ const management = new ManagementActions(asyncJobTracker, nativeRuns, void 0, teamChannel, options.observe);
6932
7064
  const subagentTool = new SubagentToolService(spawnPlanner, management, asyncJobTracker, discovery, options.discoveryIo);
6933
7065
  const dispose = () => {};
6934
7066
  return Object.freeze({
@@ -7109,7 +7241,7 @@ function recordDelegationObservation(telemetry, observation) {
7109
7241
  "run.id": event.runId,
7110
7242
  "team.tool_count": event.toolCount ?? 0,
7111
7243
  "team.duration_ms": event.durationMs ?? 0,
7112
- "team.token_count": event.tokens ?? 0,
7244
+ "team.usage_count": event.tokens ?? 0,
7113
7245
  outcome: event.status ?? "updated"
7114
7246
  });
7115
7247
  } else if (observation.kind === "finished") {
@@ -7140,7 +7272,10 @@ const root = (0, _agimon_ai_po_core_extensionFile.defineRoot)(async ({ context,
7140
7272
  serviceName: "po-team",
7141
7273
  packageName: "@agimon-ai/po-team",
7142
7274
  cwd: execution.cwd,
7143
- env: serverHost.context.environment,
7275
+ env: {
7276
+ ...serverHost.context.environment,
7277
+ AGENT_SESSION_ID: execution.sessionId
7278
+ },
7144
7279
  enableLogs: true,
7145
7280
  enableTraces: true
7146
7281
  });
@@ -7166,7 +7301,10 @@ const root = (0, _agimon_ai_po_core_extensionFile.defineRoot)(async ({ context,
7166
7301
  homeDirectory
7167
7302
  }),
7168
7303
  childSessions: { get: () => (0, _agimon_ai_po_core_childSession.readPoChildSessionService)(context) },
7169
- nativeRunProjection
7304
+ nativeRunProjection,
7305
+ observe: (event, attributes) => {
7306
+ telemetry.recordEvent(event, attributes);
7307
+ }
7170
7308
  });
7171
7309
  const awaitedInline = createAwaitedInlineRunner({
7172
7310
  execution,
@@ -7186,7 +7324,8 @@ const root = (0, _agimon_ai_po_core_extensionFile.defineRoot)(async ({ context,
7186
7324
  scheduler: runtime.pollScheduler,
7187
7325
  tracker: runtime.asyncJobTracker,
7188
7326
  loadConfig: () => sessionConfig,
7189
- readTranscript: (sessionId, runId, limit) => runtime.nativeRuns.readTranscript(sessionId, runId, limit)
7327
+ readTranscript: (sessionId, runId, limit) => runtime.nativeRuns.readTranscript(sessionId, runId, limit),
7328
+ canResume: () => runtime.nativeRuns.canResume()
7190
7329
  });
7191
7330
  const nativeRuns = /* @__PURE__ */ new Map();
7192
7331
  const childCosts = /* @__PURE__ */ new Map();
@@ -7957,10 +8096,10 @@ function createTeamSessionApi(runtime, execution, config) {
7957
8096
  }),
7958
8097
  invalidate: () => runtime.discovery.invalidate(),
7959
8098
  launch,
7960
- steer: (request, signal) => runtime.management.steer(request.runId, {
8099
+ steer: (request, signal) => runtime.management.steerOrResume(request.runId, {
7961
8100
  text: request.message,
7962
8101
  sender: HUMAN_SENDER
7963
- }, void 0, signal),
8102
+ }, signal),
7964
8103
  stop: (request) => runtime.management.stop(request.runId)
7965
8104
  })
7966
8105
  };