@wrongstack/core 0.10.2 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/{agent-bridge-DBBGP5O4.d.ts → agent-bridge-D_XcS2HL.d.ts} +3 -1
  2. package/dist/{agent-subagent-runner-KwufTWwn.d.ts → agent-subagent-runner-DuRtZmhl.d.ts} +13 -3
  3. package/dist/coordination/index.d.ts +8 -8
  4. package/dist/coordination/index.js +83 -21
  5. package/dist/coordination/index.js.map +1 -1
  6. package/dist/defaults/index.d.ts +11 -11
  7. package/dist/defaults/index.js +89 -23
  8. package/dist/defaults/index.js.map +1 -1
  9. package/dist/{events-Bw1K5E6K.d.ts → events-BrQiweXN.d.ts} +1 -1
  10. package/dist/execution/index.d.ts +6 -6
  11. package/dist/execution/index.js +32 -10
  12. package/dist/execution/index.js.map +1 -1
  13. package/dist/extension/index.d.ts +2 -2
  14. package/dist/{index-DgQWnZxP.d.ts → index-DAHEM_II.d.ts} +1 -1
  15. package/dist/{index-DIt5TIaF.d.ts → index-DnBHrz2y.d.ts} +2 -2
  16. package/dist/index.d.ts +17 -17
  17. package/dist/index.js +226 -101
  18. package/dist/index.js.map +1 -1
  19. package/dist/infrastructure/index.d.ts +2 -2
  20. package/dist/kernel/index.d.ts +3 -3
  21. package/dist/kernel/index.js.map +1 -1
  22. package/dist/{multi-agent-C1O8EFzb.d.ts → multi-agent-C8Z1i__e.d.ts} +2 -2
  23. package/dist/{multi-agent-coordinator-DoVSBFNx.d.ts → multi-agent-coordinator-CjG-FZKj.d.ts} +8 -3
  24. package/dist/{null-fleet-bus-T-s3JaOt.d.ts → null-fleet-bus-B3WdVY9i.d.ts} +28 -23
  25. package/dist/observability/index.d.ts +1 -1
  26. package/dist/{path-resolver-BfyK-I7w.d.ts → path-resolver-DumKAi0n.d.ts} +1 -1
  27. package/dist/{plan-templates-BWs6Je7j.d.ts → plan-templates-BUP4o-ds.d.ts} +2 -2
  28. package/dist/{provider-runner-BmPe2RuU.d.ts → provider-runner-Dlv8Fvw9.d.ts} +1 -1
  29. package/dist/sdd/index.d.ts +4 -4
  30. package/dist/sdd/index.js +30 -8
  31. package/dist/sdd/index.js.map +1 -1
  32. package/dist/security/index.js +3 -3
  33. package/dist/security/index.js.map +1 -1
  34. package/dist/{session-reader-CCSBfQmd.d.ts → session-reader-bfgsy2a0.d.ts} +7 -3
  35. package/dist/storage/index.d.ts +29 -10
  36. package/dist/storage/index.js +131 -65
  37. package/dist/storage/index.js.map +1 -1
  38. package/dist/{tool-executor-D7RxLtg4.d.ts → tool-executor-D87-_5Of.d.ts} +1 -1
  39. package/dist/types/index.d.ts +8 -8
  40. package/dist/types/index.js +25 -5
  41. package/dist/types/index.js.map +1 -1
  42. package/package.json +1 -1
@@ -1,19 +1,19 @@
1
1
  export { D as DefaultLogger, a as DefaultLoggerOptions } from '../logger-bOzkF5LL.js';
2
- export { A as AbandonedSession, a as AttachmentStoreOptions, C as ConfigLoaderOptions, b as ConfigMigration, c as ConfigMigrationError, d as ConfigSource, D as DEFAULT_CONFIG_MIGRATIONS, e as DefaultAttachmentStore, f as DefaultConfigLoader, g as DefaultConfigStore, h as DefaultMemoryStore, i as DefaultSessionStore, M as MemoryStoreOptions, j as MigrationContext, k as MigrationResult, P as PersistedQueueItem, l as PlanFile, m as PlanItem, n as PlanTemplate, Q as QueueStore, R as RecoveryLock, o as RecoveryLockOptions, S as SessionAnalyzer, p as SessionStoreOptions, T as TodosCheckpointFile, q as addPlanItem, r as attachPlanCheckpoint, s as attachTodosCheckpoint, t as clearPlan, u as deriveTodosFromPlanItem, v as emptyPlan, w as formatPlan, x as formatPlanTemplates, y as getPlanTemplate, z as listPlanTemplates, B as loadPlan, E as loadTodosCheckpoint, F as removePlanItem, G as runConfigMigrations, H as savePlan, I as saveTodosCheckpoint, J as setPlanItemStatus } from '../plan-templates-BWs6Je7j.js';
3
- export { D as DefaultSessionReader } from '../session-reader-CCSBfQmd.js';
2
+ export { A as AbandonedSession, a as AttachmentStoreOptions, C as ConfigLoaderOptions, b as ConfigMigration, c as ConfigMigrationError, d as ConfigSource, D as DEFAULT_CONFIG_MIGRATIONS, e as DefaultAttachmentStore, f as DefaultConfigLoader, g as DefaultConfigStore, h as DefaultMemoryStore, i as DefaultSessionStore, M as MemoryStoreOptions, j as MigrationContext, k as MigrationResult, P as PersistedQueueItem, l as PlanFile, m as PlanItem, n as PlanTemplate, Q as QueueStore, R as RecoveryLock, o as RecoveryLockOptions, S as SessionAnalyzer, p as SessionStoreOptions, T as TodosCheckpointFile, q as addPlanItem, r as attachPlanCheckpoint, s as attachTodosCheckpoint, t as clearPlan, u as deriveTodosFromPlanItem, v as emptyPlan, w as formatPlan, x as formatPlanTemplates, y as getPlanTemplate, z as listPlanTemplates, B as loadPlan, E as loadTodosCheckpoint, F as removePlanItem, G as runConfigMigrations, H as savePlan, I as saveTodosCheckpoint, J as setPlanItemStatus } from '../plan-templates-BUP4o-ds.js';
3
+ export { D as DefaultSessionReader } from '../session-reader-bfgsy2a0.js';
4
4
  export { A as AuditLevel, a as SessionEventBridge, b as SessionEventBridgeOptions, c as SessionSamplingOptions, T as ToolProgressSamplingOptions, e as createSessionEventBridge, r as resolveAuditLevel, i as resolveSessionLoggingConfig } from '../goal-store-BeRsj7YX.js';
5
5
  export { D as DirectorStateCheckpoint, a as DirectorStateSnapshot, b as DirectorSubagentState, c as DirectorTaskState, l as loadDirectorState } from '../director-state-BmYi3DGA.js';
6
6
  export { D as DefaultSecretScrubber, a as DefaultSecretVault, S as SecretVaultOptions, d as decryptConfigSecrets, e as encryptConfigSecrets, m as migratePlaintextSecrets, r as rewriteConfigEncrypted } from '../secret-scrubber-7rSC_emZ.js';
7
7
  export { A as AutoApprovePermissionPolicy, D as DefaultPermissionPolicy, P as PermissionPolicyOptions } from '../permission-policy-CtNscWOA.js';
8
- export { C as CompactorOptions, a as DefaultErrorHandler, b as DefaultRetryPolicy, H as HybridCompactor, T as ToolExecutor } from '../tool-executor-D7RxLtg4.js';
8
+ export { C as CompactorOptions, a as DefaultErrorHandler, b as DefaultRetryPolicy, H as HybridCompactor, T as ToolExecutor } from '../tool-executor-D87-_5Of.js';
9
9
  export { AutoCompactionMiddleware, AutonomousRunner, AutonomousRunnerOptions, AutonomyPromptContributorOptions, DefaultSkillLoader, DoneCheckResult, DoneConditionChecker, EternalAutonomyEngine, EternalAutonomyOptions, EternalEngineState, IntelligentCompactor, IntelligentCompactorOptions, ParallelEngineState, ParallelEternalEngine, ParallelEternalOptions, SelectiveCompactor, SelectiveCompactorOptions, SkillLoaderOptions, buildGoalPreamble, makeAutonomyPromptContributor } from '../execution/index.js';
10
- import { P as ProviderRunner, R as RunProviderOptions } from '../provider-runner-BmPe2RuU.js';
10
+ import { P as ProviderRunner, R as RunProviderOptions } from '../provider-runner-Dlv8Fvw9.js';
11
11
  import { q as Response } from '../context-7u93AcGD.js';
12
- export { a as AGENTS_BY_PHASE, b as AGENT_CATALOG, c as ALL_AGENT_DEFINITIONS, d as ALL_FLEET_AGENTS, e as AUDIT_LOG_AGENT, f as AutoExtendCeiling, g as AutoExtendPolicy, B as BUG_HUNTER_AGENT, n as CreateDelegateToolOptions, D as DEFAULT_DIRECTOR_PREAMBLE, q as DEFAULT_SUBAGENT_BASELINE, r as DelegateHost, s as Director, w as DirectorPromptParts, x as DirectorSessionFactory, y as DirectorSessionFactoryOptions, F as FLEET_ROSTER, z as FLEET_ROSTER_BUDGETS, J as FleetRosterBudget, K as FleetSpawnBudgetError, L as ICoordinator, M as IFleetManager, N as NULL_FLEET_BUS, R as REFACTOR_PLANNER_AGENT, S as SECURITY_SCANNER_AGENT, U as SubagentPromptParts, V as applyRosterBudget, W as attachAutoExtend, X as composeDirectorPrompt, Y as composeSubagentPrompt, Z as createDelegateTool, _ as getAgentDefinition, $ as makeAskTool, a0 as makeAssignTool, a1 as makeAwaitTasksTool, a2 as makeCollabDebugTool, a3 as makeDirectorSessionFactory, a4 as makeFleetEmitTool, a5 as makeFleetHealthTool, a6 as makeFleetSessionTool, a7 as makeFleetStatusTool, a8 as makeFleetUsageTool, a9 as makeRollUpTool, aa as makeSpawnTool, ab as makeTerminateTool, ad as rosterSummaryFromConfigs } from '../null-fleet-bus-T-s3JaOt.js';
13
- export { A as AgentBudgetTier, a as AgentCapability, b as AgentDefinition, c as AgentPhase, D as DEFAULT_DISPATCH_ROLE, d as DefaultMultiAgentCoordinator, e as DispatchCandidate, f as DispatchClassifier, g as DispatchMethod, h as DispatchOptions, i as DispatchResult, j as MultiAgentCoordinatorOptions, k as dispatchAgent, m as makeLLMClassifier, s as scoreAgents } from '../multi-agent-coordinator-DoVSBFNx.js';
14
- export { c as BudgetExceededError, d as BudgetKind, e as BudgetLimits, j as BudgetUsage, m as SubagentBudget } from '../multi-agent-C1O8EFzb.js';
15
- export { A as AgentFactory, a as AgentFactoryResult, b as AgentRunnerOptions, F as FleetBus, c as FleetEvent, d as FleetHandler, e as FleetUsage, f as FleetUsageAggregator, S as SubagentUsageSnapshot, m as makeAgentSubagentRunner } from '../agent-subagent-runner-KwufTWwn.js';
16
- export { I as InMemoryAgentBridge, a as InMemoryBridgeTransport, c as createMessage } from '../agent-bridge-DBBGP5O4.js';
12
+ export { a as AGENTS_BY_PHASE, b as AGENT_CATALOG, c as ALL_AGENT_DEFINITIONS, d as ALL_FLEET_AGENTS, e as AUDIT_LOG_AGENT, f as AutoExtendCeiling, g as AutoExtendPolicy, B as BUG_HUNTER_AGENT, n as CreateDelegateToolOptions, D as DEFAULT_DIRECTOR_PREAMBLE, q as DEFAULT_SUBAGENT_BASELINE, r as DelegateHost, s as Director, w as DirectorPromptParts, x as DirectorSessionFactory, y as DirectorSessionFactoryOptions, F as FLEET_ROSTER, z as FLEET_ROSTER_BUDGETS, J as FleetRosterBudget, K as FleetSpawnBudgetError, L as ICoordinator, M as IFleetManager, N as NULL_FLEET_BUS, R as REFACTOR_PLANNER_AGENT, S as SECURITY_SCANNER_AGENT, U as SubagentPromptParts, V as applyRosterBudget, W as attachAutoExtend, X as composeDirectorPrompt, Y as composeSubagentPrompt, Z as createDelegateTool, _ as getAgentDefinition, $ as makeAskTool, a0 as makeAssignTool, a1 as makeAwaitTasksTool, a2 as makeCollabDebugTool, a3 as makeDirectorSessionFactory, a4 as makeFleetEmitTool, a5 as makeFleetHealthTool, a6 as makeFleetSessionTool, a7 as makeFleetStatusTool, a8 as makeFleetUsageTool, a9 as makeRollUpTool, aa as makeSpawnTool, ab as makeTerminateTool, ad as rosterSummaryFromConfigs } from '../null-fleet-bus-B3WdVY9i.js';
13
+ export { A as AgentBudgetTier, a as AgentCapability, b as AgentDefinition, c as AgentPhase, D as DEFAULT_DISPATCH_ROLE, d as DefaultMultiAgentCoordinator, e as DispatchCandidate, f as DispatchClassifier, g as DispatchMethod, h as DispatchOptions, i as DispatchResult, j as MultiAgentCoordinatorOptions, k as dispatchAgent, m as makeLLMClassifier, s as scoreAgents } from '../multi-agent-coordinator-CjG-FZKj.js';
14
+ export { c as BudgetExceededError, d as BudgetKind, e as BudgetLimits, j as BudgetUsage, m as SubagentBudget } from '../multi-agent-C8Z1i__e.js';
15
+ export { A as AgentFactory, a as AgentFactoryResult, b as AgentRunnerOptions, F as FleetBus, c as FleetEvent, d as FleetHandler, e as FleetUsage, f as FleetUsageAggregator, S as SubagentUsageSnapshot, m as makeAgentSubagentRunner } from '../agent-subagent-runner-DuRtZmhl.js';
16
+ export { I as InMemoryAgentBridge, a as InMemoryBridgeTransport, c as createMessage } from '../agent-bridge-D_XcS2HL.js';
17
17
  export { D as DefaultModelsRegistry, a as DefaultModelsRegistryOptions, c as classifyFamily } from '../models-registry-gwMAo6E3.js';
18
18
  export { DefaultModeStore, LLMSelector, LLMSelectorOptions, ModeLoaderOptions, loadProjectModes, loadUserModes } from '../models/index.js';
19
19
  export { AISpecBuilder, AISpecBuilderOptions, AISpecPhase, AISpecSession, AutoExecutor, AutoExecutorOptions, BottleneckTask, CollectedAnswer, CriticalPathAnalysis, DefaultTaskStore, ExecutionSummary, GeneratedTask, RunResult, SPEC_TEMPLATES, SddParallelRun, SddParallelRunOptions, SddProgress, SddTaskDecomposer, SddTaskDecomposerOptions, SpecDiff, SpecDrivenDev, SpecDrivenDevOptions, SpecIndexEntry, SpecParser, SpecStore, SpecStoreOptions, SpecVersion, SpecVersioning, TaskBatch, TaskExecutionContext, TaskExecutionResult, TaskFlow, TaskFlowEventMap, TaskFlowEventName, TaskFlowExecutionContext, TaskFlowOptions, TaskFlowPhase, TaskGenerator, TaskGeneratorOptions, TaskGraphIndexEntry, TaskGraphStore, TaskGraphStoreOptions, TaskStore, TaskTracker, TaskTrackerOptions, TaskTransition, WaveResult, analyzeCriticalPath, createAutoExecutor, getTemplate, listTemplates, renderProgress, renderSpecAnalysis, renderTaskGraph, renderTaskList, templateToMarkdown } from '../sdd/index.js';
@@ -21,7 +21,7 @@ export { DefaultHealthRegistry, InMemoryMetricsSink, MetricsServerHandle, Metric
21
21
  export { C as ContextManagerAction, a as ContextManagerInput, b as ContextManagerResult, c as ContextManagerToolOptions, d as allServers, e as awsServer, f as blockServer, g as braveSearchServer, h as context7Server, i as contextManagerTool, j as createContextManagerTool, k as everArtServer, l as filesystemServer, m as githubServer, n as googleMapsServer, o as miniMaxVisionServer, s as sentinelServer, p as slackServer, z as zaiVisionServer } from '../mcp-servers-BgINZzuo.js';
22
22
  export { D as DEFAULT_AUTONOMY_CONFIG, a as DEFAULT_CONTEXT_CONFIG, c as DEFAULT_TOOLS_CONFIG } from '../default-config-DEXI4jsl.js';
23
23
  import '../logger-DDd5C--Z.js';
24
- import '../events-Bw1K5E6K.js';
24
+ import '../events-BrQiweXN.js';
25
25
  import '../secret-scrubber-3MHDDAtm.js';
26
26
  import '../memory-CEXuo7sz.js';
27
27
  import '../wstack-paths-eMXnY1_X.js';
@@ -32,7 +32,7 @@ import '../input-reader-E-ffP2ee.js';
32
32
  import '../permission-B6sldrSp.js';
33
33
  import '../compactor-D1RHFRmF.js';
34
34
  import '../retry-policy-KF18W4dg.js';
35
- import '../index-DgQWnZxP.js';
35
+ import '../index-DAHEM_II.js';
36
36
  import '../system-prompt-CM6zOhd2.js';
37
37
  import '../observability-BhnVLBLS.js';
38
38
  import '../selector-DmXxpFyM.js';
@@ -1943,11 +1943,27 @@ var DefaultSessionReader = class {
1943
1943
  const data = await this.store.load(sessionId);
1944
1944
  for (const e of data.events) yield e;
1945
1945
  }
1946
- async search(q, sessionId) {
1946
+ async search(q, sessionId, sessionQuery) {
1947
1947
  const limit = q.limit ?? 100;
1948
1948
  const matcher = buildMatcher(q);
1949
1949
  const allowedTypes = q.types ? new Set(q.types) : null;
1950
- const ids = sessionId ? [sessionId] : (await this.store.list(1e3)).map((s) => s.id);
1950
+ let ids;
1951
+ if (sessionId) {
1952
+ ids = [sessionId];
1953
+ } else {
1954
+ const sessions = await this.store.list(1e3);
1955
+ const titleNeedle = sessionQuery?.titleContains?.toLowerCase();
1956
+ const filtered = sessions.filter((s) => {
1957
+ if (sessionQuery?.since && s.startedAt < sessionQuery.since) return false;
1958
+ if (sessionQuery?.until && s.startedAt > sessionQuery.until) return false;
1959
+ if (sessionQuery?.provider && s.provider !== sessionQuery.provider) return false;
1960
+ if (sessionQuery?.model && s.model !== sessionQuery.model) return false;
1961
+ if (sessionQuery?.minTokens !== void 0 && s.tokenTotal < sessionQuery.minTokens) return false;
1962
+ if (titleNeedle && !s.title.toLowerCase().includes(titleNeedle)) return false;
1963
+ return true;
1964
+ });
1965
+ ids = filtered.map((s) => s.id);
1966
+ }
1951
1967
  const hits = [];
1952
1968
  for (const id of ids) {
1953
1969
  let data;
@@ -3200,13 +3216,13 @@ var DANGEROUS_FOR_SUBAGENTS = [
3200
3216
  function hasDangerousCapabilityForSubagents(toolOrCaps) {
3201
3217
  if (!toolOrCaps) return false;
3202
3218
  const input = toolOrCaps;
3203
- const caps = Array.isArray(input) ? input : input?.capabilities ?? [];
3219
+ const caps = Array.isArray(toolOrCaps) ? toolOrCaps : input.capabilities ?? [];
3204
3220
  return caps.some((c) => DANGEROUS_FOR_SUBAGENTS.includes(c));
3205
3221
  }
3206
3222
  function getDangerousCapabilities(toolOrCaps) {
3207
3223
  if (!toolOrCaps) return [];
3208
3224
  const input = toolOrCaps;
3209
- const caps = Array.isArray(input) ? input : input?.capabilities ?? [];
3225
+ const caps = Array.isArray(toolOrCaps) ? toolOrCaps : input.capabilities ?? [];
3210
3226
  return caps.filter(
3211
3227
  (c) => DANGEROUS_FOR_SUBAGENTS.includes(c)
3212
3228
  );
@@ -6881,8 +6897,9 @@ var SubagentBudget = class _SubagentBudget {
6881
6897
  if (elapsedMs !== void 0) {
6882
6898
  const idle = this.idleMs();
6883
6899
  if (this.limits.idleTimeoutMs !== void 0 && idle > this.limits.idleTimeoutMs) {
6884
- exceeded.push({ kind: "timeout", used: idle, limit: this.limits.idleTimeoutMs });
6885
- } else if (this.limits.timeoutMs !== void 0 && elapsedMs > this.limits.timeoutMs) {
6900
+ exceeded.push({ kind: "idle_timeout", used: idle, limit: this.limits.idleTimeoutMs });
6901
+ }
6902
+ if (this.limits.timeoutMs !== void 0 && elapsedMs > this.limits.timeoutMs) {
6886
6903
  exceeded.push({ kind: "timeout", used: elapsedMs, limit: this.limits.timeoutMs });
6887
6904
  }
6888
6905
  }
@@ -10095,10 +10112,6 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
10095
10112
  this.drainPendingAsAborted("Coordinator stopAll() drained the pending queue");
10096
10113
  await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));
10097
10114
  }
10098
- async remove(subagentId) {
10099
- await this.stop(subagentId);
10100
- this.subagents.delete(subagentId);
10101
- }
10102
10115
  /**
10103
10116
  * Get current coordinator stats for monitoring/debugging.
10104
10117
  */
@@ -10364,7 +10377,7 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
10364
10377
  durationMs: Date.now() - startTime
10365
10378
  };
10366
10379
  } catch (err) {
10367
- const status = err instanceof BudgetExceededError && err.kind === "timeout" ? "timeout" : subagent.abortController.signal.aborted ? "stopped" : "failed";
10380
+ const status = err instanceof BudgetExceededError && (err.kind === "timeout" || err.kind === "idle_timeout") ? "timeout" : subagent.abortController.signal.aborted ? "stopped" : "failed";
10368
10381
  const usage = budget.usage();
10369
10382
  result = {
10370
10383
  subagentId,
@@ -10518,6 +10531,30 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
10518
10531
  });
10519
10532
  }
10520
10533
  }
10534
+ /**
10535
+ * Stop a subagent and remove it from the coordinator. Releases all
10536
+ * associated resources (AbortController, context, budget state).
10537
+ * The subagent entry is deleted so the id can be reused in a future spawn.
10538
+ */
10539
+ async remove(subagentId) {
10540
+ const subagent = this.subagents.get(subagentId);
10541
+ if (!subagent) return;
10542
+ if (subagent.status === "running" || subagent.status === "idle") {
10543
+ this.terminating.add(subagentId);
10544
+ subagent.abortController.abort();
10545
+ subagent.status = "stopped";
10546
+ }
10547
+ this.subagents.delete(subagentId);
10548
+ this.terminating.delete(subagentId);
10549
+ this.pendingTasks = this.pendingTasks.filter((t) => t.subagentId !== subagentId);
10550
+ this.fleetBus?.emit({
10551
+ subagentId,
10552
+ ts: Date.now(),
10553
+ type: "subagent.removed",
10554
+ payload: { subagentId }
10555
+ });
10556
+ this.emitCoordinatorStats();
10557
+ }
10521
10558
  isDone() {
10522
10559
  if (this.config.doneCondition.type === "all_tasks_done") {
10523
10560
  return this.pendingTasks.length === 0 && this.inFlight === 0;
@@ -10541,7 +10578,8 @@ function classifySubagentError(err, hints = {}) {
10541
10578
  tool_calls: "budget_tool_calls",
10542
10579
  tokens: "budget_tokens",
10543
10580
  cost: "budget_cost",
10544
- timeout: "budget_timeout"
10581
+ timeout: "budget_timeout",
10582
+ idle_timeout: "budget_timeout"
10545
10583
  };
10546
10584
  return {
10547
10585
  kind: map[err.kind],
@@ -11172,12 +11210,14 @@ var InMemoryAgentBridge = class {
11172
11210
  timeoutMs;
11173
11211
  /** Guards request() so concurrent calls on the same id can't silently overwrite. */
11174
11212
  inflightGuards = /* @__PURE__ */ new Set();
11213
+ /** Stores the transport unsubscribe function so it can be called on stop(). */
11214
+ _transportUnsubscribe;
11175
11215
  constructor(config, transport) {
11176
11216
  this.agentId = config.agentId;
11177
11217
  this.coordinatorId = config.coordinatorId;
11178
11218
  this.transport = transport;
11179
11219
  this.timeoutMs = config.timeoutMs ?? 3e4;
11180
- this.transport.subscribe(this.agentId, (msg) => {
11220
+ this._transportUnsubscribe = this.transport.subscribe(this.agentId, (msg) => {
11181
11221
  if (msg.type === "heartbeat") return;
11182
11222
  const pending = this.pendingRequests.get(msg.id);
11183
11223
  if (pending) {
@@ -11252,6 +11292,8 @@ var InMemoryAgentBridge = class {
11252
11292
  this.pendingRequests.clear();
11253
11293
  this.inflightGuards.clear();
11254
11294
  this.subscriptions.clear();
11295
+ this._transportUnsubscribe?.();
11296
+ this._transportUnsubscribe = void 0;
11255
11297
  await this.transport.close(this.agentId);
11256
11298
  }
11257
11299
  };
@@ -11447,14 +11489,36 @@ var FleetUsageAggregator = class {
11447
11489
  constructor(bus, priceLookup, metaLookup) {
11448
11490
  this.priceLookup = priceLookup;
11449
11491
  this.metaLookup = metaLookup;
11450
- bus.filter("provider.response", (e) => this.onProviderResponse(e));
11451
- bus.filter("tool.executed", (e) => this.onToolExecuted(e));
11452
- bus.filter("iteration.started", (e) => this.onIterationStarted(e));
11492
+ this.unsub.push(bus.filter("provider.response", (e) => this.onProviderResponse(e)));
11493
+ this.unsub.push(bus.filter("tool.executed", (e) => this.onToolExecuted(e)));
11494
+ this.unsub.push(bus.filter("iteration.started", (e) => this.onIterationStarted(e)));
11453
11495
  }
11454
11496
  priceLookup;
11455
11497
  metaLookup;
11456
11498
  perSubagent = /* @__PURE__ */ new Map();
11457
11499
  total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
11500
+ unsub = new Array();
11501
+ /**
11502
+ * Remove a terminated subagent's data from the aggregator and subtract its
11503
+ * contribution from the running totals. Call this when a subagent is removed
11504
+ * from the fleet so the aggregator doesn't accumulate unbounded data for
11505
+ * entities that will never emit events again.
11506
+ */
11507
+ removeSubagent(subagentId) {
11508
+ const snap = this.perSubagent.get(subagentId);
11509
+ if (!snap) return;
11510
+ this.perSubagent.delete(subagentId);
11511
+ this.total.input -= snap.input;
11512
+ this.total.output -= snap.output;
11513
+ this.total.cacheRead -= snap.cacheRead;
11514
+ this.total.cacheWrite -= snap.cacheWrite;
11515
+ this.total.cost -= snap.cost;
11516
+ }
11517
+ /** Disposes all fleet-bus subscriptions. Call when the aggregator is no longer needed. */
11518
+ dispose() {
11519
+ for (const off of this.unsub) off();
11520
+ this.unsub.length = 0;
11521
+ }
11458
11522
  /** Live snapshot — safe to call from a tool's execute() body. */
11459
11523
  snapshot() {
11460
11524
  return {
@@ -12207,7 +12271,7 @@ Emit each evaluation immediately. Do not wait until you have read all reports.`;
12207
12271
  this.cancel(`Director cancelled: ${role} ${payload.kind} threshold`);
12208
12272
  return;
12209
12273
  }
12210
- if (payload.kind === "timeout") {
12274
+ if (payload.kind === "timeout" || payload.kind === "idle_timeout") {
12211
12275
  const progress = this.progressBySubagent.get(e.subagentId) ?? 0;
12212
12276
  const lastProgress = this.lastTimeoutProgress.get(e.subagentId) ?? -1;
12213
12277
  if (progress <= lastProgress) {
@@ -12945,7 +13009,7 @@ var Director = class {
12945
13009
  if (needsNickname) {
12946
13010
  const role = config.role ?? "subagent";
12947
13011
  if (this.fleetManager) {
12948
- this.fleetManager.assignNicknameAndRecord("", config, priceLookup);
13012
+ this.fleetManager.assignNicknameAndRecord(config);
12949
13013
  } else {
12950
13014
  config.name = assignNickname(role, this._usedNicknames);
12951
13015
  this._usedNicknames.add(config.name.split(" ")[0].toLowerCase().replace(/[^a-z0-9-]/g, "-"));
@@ -12953,9 +13017,7 @@ var Director = class {
12953
13017
  }
12954
13018
  result = await this.coordinator.spawn(config);
12955
13019
  if (this.fleetManager) {
12956
- if (!needsNickname) {
12957
- this.fleetManager.recordSpawn(result.subagentId, config, priceLookup);
12958
- }
13020
+ this.fleetManager.recordSpawn(result.subagentId, config, priceLookup);
12959
13021
  } else {
12960
13022
  this.spawnCount += 1;
12961
13023
  this.subagentMeta.set(result.subagentId, {
@@ -13243,6 +13305,7 @@ var Director = class {
13243
13305
  }
13244
13306
  async remove(subagentId) {
13245
13307
  await this.coordinator.remove(subagentId);
13308
+ this.usage.removeSubagent(subagentId);
13246
13309
  }
13247
13310
  status() {
13248
13311
  const base = this.coordinator.getStatus();
@@ -13578,6 +13641,7 @@ function createDelegateTool(opts) {
13578
13641
  if (timer) clearTimeout(timer);
13579
13642
  offTool();
13580
13643
  offIter();
13644
+ offProgress();
13581
13645
  resolve3(value);
13582
13646
  };
13583
13647
  const arm = () => {
@@ -13589,6 +13653,7 @@ function createDelegateTool(opts) {
13589
13653
  };
13590
13654
  const offTool = dir.fleet.filter("tool.executed", bump);
13591
13655
  const offIter = dir.fleet.filter("iteration.started", bump);
13656
+ const offProgress = dir.fleet.filter("tool.progress", bump);
13592
13657
  arm();
13593
13658
  dir.awaitTasks([taskId]).then((r) => finish(r[0] ?? { __timeout: true })).catch(() => finish({ __timeout: true }));
13594
13659
  });
@@ -13808,7 +13873,8 @@ var FIELD_BY_KIND = {
13808
13873
  tool_calls: "maxToolCalls",
13809
13874
  tokens: "maxTokens",
13810
13875
  cost: "maxCostUsd",
13811
- timeout: "timeoutMs"
13876
+ timeout: "timeoutMs",
13877
+ idle_timeout: "timeoutMs"
13812
13878
  };
13813
13879
  function attachAutoExtend(events, policy = {}) {
13814
13880
  const factor = policy.factor ?? 0.5;
@@ -13826,7 +13892,7 @@ function attachAutoExtend(events, policy = {}) {
13826
13892
  }),
13827
13893
  events.on("budget.threshold_reached", (e) => {
13828
13894
  const { kind, limit, extend, deny } = e;
13829
- if (kind === "timeout") {
13895
+ if (kind === "timeout" || kind === "idle_timeout") {
13830
13896
  if (progress > lastTimeoutProgress) {
13831
13897
  lastTimeoutProgress = progress;
13832
13898
  const next2 = Math.min(Math.ceil(limit * (1 + factor)), ceiling.timeoutMs);