@evalops/maestro 0.10.26 → 0.10.29

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 (40) hide show
  1. package/dist/agent/transport/reusable-tool-results.d.ts +38 -0
  2. package/dist/agent/transport/reusable-tool-results.d.ts.map +1 -0
  3. package/dist/agent/transport/reusable-tool-results.js +432 -0
  4. package/dist/agent/transport/reusable-tool-results.js.map +1 -0
  5. package/dist/agent/transport.d.ts +1 -1
  6. package/dist/agent/transport.d.ts.map +1 -1
  7. package/dist/agent/transport.js +1 -430
  8. package/dist/agent/transport.js.map +1 -1
  9. package/dist/audit/logger.d.ts +2 -2
  10. package/dist/cli/commands/run.d.ts +15 -0
  11. package/dist/cli/commands/run.d.ts.map +1 -1
  12. package/dist/cli/commands/run.js +35 -0
  13. package/dist/cli/commands/run.js.map +1 -1
  14. package/dist/cli.js +750 -632
  15. package/dist/node_modules/@evalops/contracts/package.json +1 -1
  16. package/dist/node_modules/@evalops/tui/package.json +1 -1
  17. package/dist/platform/agent-registry-client.d.ts +6 -0
  18. package/dist/platform/agent-registry-client.d.ts.map +1 -1
  19. package/dist/platform/agent-registry-client.js +6 -0
  20. package/dist/platform/agent-registry-client.js.map +1 -1
  21. package/dist/server/agent-runtime-ledger.d.ts +5 -0
  22. package/dist/server/agent-runtime-ledger.d.ts.map +1 -1
  23. package/dist/server/agent-runtime-ledger.js +63 -0
  24. package/dist/server/agent-runtime-ledger.js.map +1 -1
  25. package/dist/server/headless-runtime/broker.d.ts +81 -0
  26. package/dist/server/headless-runtime/broker.d.ts.map +1 -0
  27. package/dist/server/headless-runtime/broker.js +201 -0
  28. package/dist/server/headless-runtime/broker.js.map +1 -0
  29. package/dist/server/headless-runtime-service.d.ts +3 -37
  30. package/dist/server/headless-runtime-service.d.ts.map +1 -1
  31. package/dist/server/headless-runtime-service.js +1 -199
  32. package/dist/server/headless-runtime-service.js.map +1 -1
  33. package/dist/session/manager.d.ts +1 -0
  34. package/dist/session/manager.d.ts.map +1 -1
  35. package/dist/session/manager.js.map +1 -1
  36. package/dist/tools/parallel-ripgrep.d.ts.map +1 -1
  37. package/dist/tools/parallel-ripgrep.js +11 -2
  38. package/dist/tools/parallel-ripgrep.js.map +1 -1
  39. package/dist/version.json +2 -2
  40. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -36701,34 +36701,34 @@ import {
36701
36701
  BedrockRuntimeClient,
36702
36702
  ConverseStreamCommand
36703
36703
  } from "@aws-sdk/client-bedrock-runtime";
36704
+ import { execFileSync as execFileSync2 } from "node:child_process";
36705
+ import { createHash as createHash13 } from "node:crypto";
36706
+ import { readFileSync as readFileSync16 } from "node:fs";
36707
+ import { resolve as resolvePath } from "node:path";
36704
36708
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
36705
36709
  import { constants as constants2 } from "node:fs";
36706
36710
  import { access as access2, realpath, stat as stat32 } from "node:fs/promises";
36707
36711
  import { basename as basename7, isAbsolute as isAbsolute6, normalize as normalize2, resolve as resolve19, sep as sep2 } from "node:path";
36708
36712
  import { Ajv as Ajv2 } from "ajv";
36709
36713
  import addFormatsModule from "ajv-formats";
36710
- import { readFileSync as readFileSync16 } from "node:fs";
36714
+ import { readFileSync as readFileSync17 } from "node:fs";
36711
36715
  import { isAbsolute as isAbsolute7, join as join25 } from "node:path";
36712
36716
  import {
36713
36717
  parse as parseJsonc,
36714
36718
  printParseErrorCode
36715
36719
  } from "jsonc-parser";
36716
- import { existsSync as existsSync22, readFileSync as readFileSync17, statSync as statSync7 } from "node:fs";
36720
+ import { existsSync as existsSync22, readFileSync as readFileSync18, statSync as statSync7 } from "node:fs";
36717
36721
  import { dirname as dirname13, join as join26 } from "node:path";
36718
36722
  import { Type as Type6 } from "@sinclair/typebox";
36719
36723
  import { existsSync as existsSync23 } from "node:fs";
36720
36724
  import { join as join27 } from "node:path";
36721
- import { existsSync as existsSync24, readFileSync as readFileSync18, statSync as statSync8 } from "node:fs";
36725
+ import { existsSync as existsSync24, readFileSync as readFileSync19, statSync as statSync8 } from "node:fs";
36722
36726
  import { dirname as dirname14, isAbsolute as isAbsolute8, join as join28 } from "node:path";
36723
36727
  import { Value } from "@sinclair/typebox/value";
36724
36728
  import {
36725
36729
  Ajv as Ajv3
36726
36730
  } from "ajv";
36727
36731
  import addFormatsModule2 from "ajv-formats";
36728
- import { execFileSync as execFileSync2 } from "node:child_process";
36729
- import { createHash as createHash13 } from "node:crypto";
36730
- import { readFileSync as readFileSync19 } from "node:fs";
36731
- import { resolve as resolvePath } from "node:path";
36732
36732
  import { Type as Type7 } from "@sinclair/typebox";
36733
36733
  import {
36734
36734
  existsSync as existsSync25,
@@ -37596,13 +37596,17 @@ import {
37596
37596
  import { and as and7, eq as eq9, gt as gt2, lt as lt3, or as or2, sql as sql7 } from "drizzle-orm";
37597
37597
  import crypto9 from "node:crypto";
37598
37598
  import { readFileSync as readFileSync73 } from "node:fs";
37599
+ import {
37600
+ assertHeadlessFromAgentMessage as assertHeadlessFromAgentMessage2,
37601
+ assertHeadlessRuntimeStreamEnvelope
37602
+ } from "@evalops/contracts";
37599
37603
  import { createHash as createHash25 } from "node:crypto";
37600
37604
  import { readFile as readFile15 } from "node:fs/promises";
37601
37605
  import {
37602
- assertHeadlessFromAgentMessage as assertHeadlessFromAgentMessage2,
37606
+ assertHeadlessFromAgentMessage as assertHeadlessFromAgentMessage3,
37603
37607
  assertHeadlessRuntimeHeartbeatSnapshot,
37604
37608
  assertHeadlessRuntimeSnapshot,
37605
- assertHeadlessRuntimeStreamEnvelope,
37609
+ assertHeadlessRuntimeStreamEnvelope as assertHeadlessRuntimeStreamEnvelope2,
37606
37610
  assertHeadlessRuntimeSubscriptionSnapshot
37607
37611
  } from "@evalops/contracts";
37608
37612
  import { and as and8, eq as eq10 } from "drizzle-orm";
@@ -37761,7 +37765,7 @@ import { clearLine, cursorTo } from "node:readline";
37761
37765
  import { createInterface as createInterface3 } from "node:readline/promises";
37762
37766
  import {
37763
37767
  assertHeadlessRuntimeHeartbeatSnapshot as assertHeadlessRuntimeHeartbeatSnapshot2,
37764
- assertHeadlessRuntimeStreamEnvelope as assertHeadlessRuntimeStreamEnvelope2,
37768
+ assertHeadlessRuntimeStreamEnvelope as assertHeadlessRuntimeStreamEnvelope3,
37765
37769
  assertHeadlessRuntimeSubscriptionSnapshot as assertHeadlessRuntimeSubscriptionSnapshot2,
37766
37770
  headlessProtocolVersion as headlessProtocolVersion2
37767
37771
  } from "@evalops/contracts";
@@ -46296,6 +46300,7 @@ function normalizeDiscoveryEvidence(record) {
46296
46300
  schema: firstString(record, "schema"),
46297
46301
  decision: firstString(record, "decision"),
46298
46302
  reason: firstString(record, "reason"),
46303
+ organizationId: firstString(record, "organizationId", "organization_id"),
46299
46304
  workspaceId: firstString(record, "workspaceId", "workspace_id"),
46300
46305
  capability: firstString(record, "capability"),
46301
46306
  capabilities: stringList2(record, "capabilities"),
@@ -46303,10 +46308,15 @@ function normalizeDiscoveryEvidence(record) {
46303
46308
  a2aSkillId: firstString(record, "a2aSkillId", "a2a_skill_id"),
46304
46309
  taskClass: firstString(record, "taskClass", "task_class"),
46305
46310
  requireA2ADispatch: firstBoolean(record, "requireA2aDispatch", "requireA2ADispatch", "require_a2a_dispatch"),
46311
+ eligibleForDelegation: firstBoolean(record, "eligibleForDelegation", "eligible_for_delegation"),
46306
46312
  surface: firstString(record, "surface"),
46307
46313
  status: firstString(record, "status"),
46308
46314
  candidateCount: firstNumber(record, "candidateCount", "candidate_count"),
46309
46315
  matchedCount: firstNumber(record, "matchedCount", "matched_count"),
46316
+ traceId: firstString(record, "traceId", "trace_id"),
46317
+ spanId: firstString(record, "spanId", "span_id"),
46318
+ requestId: firstString(record, "requestId", "request_id"),
46319
+ observedAt: firstString(record, "observedAt", "observed_at"),
46310
46320
  exclusions: objectList(record, "exclusions")?.map((exclusion) => normalizeDiscoveryExclusion(exclusion)).filter((exclusion) => exclusion !== void 0)
46311
46321
  });
46312
46322
  }
@@ -73037,6 +73047,409 @@ var init_tool_execution_bridge = __esm2(() => {
73037
73047
  "-r"
73038
73048
  ]);
73039
73049
  });
73050
+ function hashReusableToolResultSnapshot(value) {
73051
+ return createHash13("sha256").update(value).digest("hex");
73052
+ }
73053
+ function readGitSnapshotBuffer(cwd, args) {
73054
+ return execFileSync2("git", args, {
73055
+ cwd,
73056
+ stdio: ["ignore", "pipe", "ignore"],
73057
+ timeout: REUSABLE_TOOL_RESULT_GIT_SNAPSHOT_TIMEOUT_MS
73058
+ });
73059
+ }
73060
+ function readGitSnapshotPart(cwd, args) {
73061
+ return readGitSnapshotBuffer(cwd, args).toString("utf8").trim();
73062
+ }
73063
+ function hashGitSnapshotPart(cwd, args) {
73064
+ return hashReusableToolResultSnapshot(readGitSnapshotBuffer(cwd, args));
73065
+ }
73066
+ function hashUntrackedGitFiles(root) {
73067
+ const files = readGitSnapshotBuffer(root, [
73068
+ "ls-files",
73069
+ "--others",
73070
+ "--exclude-standard",
73071
+ "-z"
73072
+ ]).toString("utf8").split("\0").filter(Boolean).sort();
73073
+ const hash = createHash13("sha256");
73074
+ for (const file of files) {
73075
+ hash.update(file);
73076
+ hash.update("\0");
73077
+ hash.update(readFileSync16(resolvePath(root, file)));
73078
+ hash.update("\0");
73079
+ }
73080
+ return hash.digest("hex");
73081
+ }
73082
+ function hasDirtyGitSubmodules(root) {
73083
+ try {
73084
+ return readGitSnapshotPart(root, [
73085
+ "submodule",
73086
+ "foreach",
73087
+ "--recursive",
73088
+ "--quiet",
73089
+ "git status --porcelain=v1 --untracked-files=all"
73090
+ ]).length > 0;
73091
+ } catch {
73092
+ return true;
73093
+ }
73094
+ }
73095
+ function computeReusableToolResultSnapshot(cwd) {
73096
+ try {
73097
+ const root = readGitSnapshotPart(cwd, ["rev-parse", "--show-toplevel"]);
73098
+ const head = readGitSnapshotPart(cwd, ["rev-parse", "--verify", "HEAD"]);
73099
+ const status = readGitSnapshotPart(root, [
73100
+ "status",
73101
+ "--porcelain=v1",
73102
+ "--untracked-files=all"
73103
+ ]);
73104
+ if (hasDirtyGitSubmodules(root)) {
73105
+ return;
73106
+ }
73107
+ const unstagedDiff = hashGitSnapshotPart(root, [
73108
+ "diff",
73109
+ "--no-ext-diff",
73110
+ "--binary"
73111
+ ]);
73112
+ const stagedDiff = hashGitSnapshotPart(root, [
73113
+ "diff",
73114
+ "--cached",
73115
+ "--no-ext-diff",
73116
+ "--binary"
73117
+ ]);
73118
+ const untracked = hashUntrackedGitFiles(root);
73119
+ return `git:${hashReusableToolResultSnapshot(`${root}
73120
+ ${head}
73121
+ ${status}
73122
+ ${unstagedDiff}
73123
+ ${stagedDiff}
73124
+ ${untracked}`)}`;
73125
+ } catch {
73126
+ return;
73127
+ }
73128
+ }
73129
+ function collectStringValues(value) {
73130
+ if (typeof value === "string") {
73131
+ return [value];
73132
+ }
73133
+ if (Array.isArray(value)) {
73134
+ return value.flatMap((item) => collectStringValues(item));
73135
+ }
73136
+ return [];
73137
+ }
73138
+ function isRepoRelativePathArgument(value) {
73139
+ const trimmed = value.trim();
73140
+ if (trimmed.length === 0) {
73141
+ return false;
73142
+ }
73143
+ if (trimmed.startsWith("/") || trimmed.startsWith("~") || trimmed.startsWith("\\\\") || /^[A-Za-z]:[\\/]/.test(trimmed)) {
73144
+ return false;
73145
+ }
73146
+ return !trimmed.split(/[\\/]+/).includes("..");
73147
+ }
73148
+ function isGitIgnoredRepoPath(cwd, repoPath) {
73149
+ try {
73150
+ readGitSnapshotPart(cwd, ["check-ignore", "--quiet", "--", repoPath]);
73151
+ return true;
73152
+ } catch (error) {
73153
+ if (typeof error === "object" && error !== null && "status" in error && error.status === 1) {
73154
+ return false;
73155
+ }
73156
+ return true;
73157
+ }
73158
+ }
73159
+ function isToolCallIncludingIgnoredPaths(toolCall) {
73160
+ const toolName = toolCall.name.toLowerCase();
73161
+ const args = toolCall.arguments;
73162
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
73163
+ return false;
73164
+ }
73165
+ const record = args;
73166
+ if (toolName === "status") {
73167
+ return record.includeIgnored === true || record.include_ignored === true;
73168
+ }
73169
+ if (toolName === "search" || toolName === "parallel_ripgrep") {
73170
+ return record.useGitIgnore === false || record.use_git_ignore === false;
73171
+ }
73172
+ return false;
73173
+ }
73174
+ function hasRepoScopedReusableArguments(toolCall, cwd) {
73175
+ const toolName = toolCall.name.toLowerCase();
73176
+ if (isToolCallIncludingIgnoredPaths(toolCall)) {
73177
+ return false;
73178
+ }
73179
+ const argumentNames = REPO_PATH_ARGUMENTS_BY_TOOL.get(toolName) ?? [];
73180
+ if (argumentNames.length === 0) {
73181
+ return true;
73182
+ }
73183
+ const args = toolCall.arguments;
73184
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
73185
+ return !REQUIRED_REPO_PATH_ARGUMENT_TOOLS.has(toolName);
73186
+ }
73187
+ const pathValues = argumentNames.flatMap((name) => collectStringValues(args[name]));
73188
+ if (pathValues.length === 0 && REQUIRED_REPO_PATH_ARGUMENT_TOOLS.has(toolName)) {
73189
+ return false;
73190
+ }
73191
+ return pathValues.every((pathValue) => isRepoRelativePathArgument(pathValue) && !isGitIgnoredRepoPath(cwd, pathValue));
73192
+ }
73193
+ function isGitSnapshotReusableToolCall(tool, toolCall, cwd) {
73194
+ if (tool.source !== void 0 || tool.annotations?.openWorldHint === true || tool.executionLocation === "client") {
73195
+ return false;
73196
+ }
73197
+ if (!GIT_SNAPSHOT_REUSABLE_TOOL_NAMES.has(tool.name.toLowerCase())) {
73198
+ return false;
73199
+ }
73200
+ if (!isReadOnlyTool(tool.name, tool.annotations, tool.source)) {
73201
+ return false;
73202
+ }
73203
+ return hasRepoScopedReusableArguments(toolCall, cwd);
73204
+ }
73205
+ function getReusableToolDefinitionIdentity(value) {
73206
+ const existing = reusableToolDefinitionIdentities.get(value);
73207
+ if (existing !== void 0) {
73208
+ return existing;
73209
+ }
73210
+ reusableToolDefinitionIdentityCounter += 1;
73211
+ reusableToolDefinitionIdentities.set(value, reusableToolDefinitionIdentityCounter);
73212
+ return reusableToolDefinitionIdentityCounter;
73213
+ }
73214
+ function getReusableToolFunctionIdentity(value) {
73215
+ return typeof value === "function" ? getReusableToolDefinitionIdentity(value) : void 0;
73216
+ }
73217
+ function getReusableToolRegistrySignature(tools) {
73218
+ return stableStringify(tools.map((tool) => ({
73219
+ allowedCallers: tool.allowedCallers,
73220
+ annotations: tool.annotations,
73221
+ deferApiDefinition: tool.deferApiDefinition,
73222
+ description: tool.description,
73223
+ executeIdentity: getReusableToolFunctionIdentity(tool.execute),
73224
+ executionLocation: tool.executionLocation,
73225
+ getActivityDescriptionIdentity: getReusableToolFunctionIdentity(tool.getActivityDescription),
73226
+ getDisplayNameIdentity: getReusableToolFunctionIdentity(tool.getDisplayName),
73227
+ getToolUseSummaryIdentity: getReusableToolFunctionIdentity(tool.getToolUseSummary),
73228
+ inputExamples: tool.inputExamples,
73229
+ label: tool.label,
73230
+ maxRetries: tool.maxRetries,
73231
+ name: tool.name,
73232
+ parameters: tool.parameters,
73233
+ retryDelayMs: tool.retryDelayMs,
73234
+ shouldRetryIdentity: getReusableToolFunctionIdentity(tool.shouldRetry),
73235
+ source: tool.source,
73236
+ toolIdentity: getReusableToolDefinitionIdentity(tool),
73237
+ toolType: tool.toolType
73238
+ })));
73239
+ }
73240
+ function createToolMetadataCache(tools, reusableToolResultCwd = process.cwd()) {
73241
+ const definitions = new Map(tools.map((tool) => [tool.name, tool]));
73242
+ return {
73243
+ definitions,
73244
+ reusableToolResultCwd,
73245
+ lookupCount: 0,
73246
+ get(toolName) {
73247
+ this.lookupCount += 1;
73248
+ return definitions.get(toolName);
73249
+ }
73250
+ };
73251
+ }
73252
+ function getToolDefinition(lookup2, toolName) {
73253
+ if ("get" in lookup2 && !Array.isArray(lookup2)) {
73254
+ return lookup2.get(toolName);
73255
+ }
73256
+ return lookup2.find((candidate) => candidate.name === toolName);
73257
+ }
73258
+ function getReusableToolResultCacheKey(toolCall, tools) {
73259
+ const tool = getToolDefinition(tools, toolCall.name);
73260
+ const cwd = "reusableToolResultCwd" in tools ? tools.reusableToolResultCwd : process.cwd();
73261
+ if (!tool || tool.annotations?.destructiveHint === true) {
73262
+ return;
73263
+ }
73264
+ if (!isReadOnlyTool(tool.name, tool.annotations, tool.source)) {
73265
+ return;
73266
+ }
73267
+ const toolName = tool.name.toLowerCase();
73268
+ const cacheKey = `${toolCall.name}:${stableStringify(toolCall.arguments)}`;
73269
+ if (NETWORK_BACKED_REUSABLE_TOOL_DENYLIST.has(toolName)) {
73270
+ return;
73271
+ }
73272
+ if (isGitSnapshotReusableToolCall(tool, toolCall, cwd)) {
73273
+ return `${GIT_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX}${cacheKey}`;
73274
+ }
73275
+ if (tool.source !== void 0 || GIT_SNAPSHOT_REUSABLE_TOOL_NAMES.has(toolName) || tool.annotations?.openWorldHint === true || tool.executionLocation === "client") {
73276
+ return;
73277
+ }
73278
+ return `${RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX}${cacheKey}`;
73279
+ }
73280
+ function isReadOnlyToolCallForCacheInvalidation(toolCall, tools) {
73281
+ const tool = getToolDefinition(tools, toolCall.name);
73282
+ return tool ? isReadOnlyTool(tool.name, tool.annotations, tool.source) : false;
73283
+ }
73284
+ function cloneToolResultForCache(message) {
73285
+ return {
73286
+ ...message,
73287
+ content: message.content.map((item) => ({ ...item }))
73288
+ };
73289
+ }
73290
+ function cloneToolOutcomeForCall(outcome, toolCall, timestamp3) {
73291
+ return {
73292
+ message: {
73293
+ ...outcome.message,
73294
+ toolCallId: toolCall.id,
73295
+ toolName: toolCall.name,
73296
+ content: outcome.message.content.map((item) => ({ ...item })),
73297
+ timestamp: timestamp3
73298
+ },
73299
+ isError: outcome.isError
73300
+ };
73301
+ }
73302
+ function resolvePlatformToolExecutionBridge(option) {
73303
+ if (option === false) {
73304
+ return;
73305
+ }
73306
+ return option ?? getDefaultPlatformToolExecutionBridge();
73307
+ }
73308
+ async function recordReusableToolExecutionBridgeOutput({
73309
+ bridge,
73310
+ plan,
73311
+ outcome,
73312
+ durationMs,
73313
+ signal
73314
+ }) {
73315
+ if (!bridge || !plan) {
73316
+ return outcome;
73317
+ }
73318
+ const observed = plan.kind === "observe" ? await bridge.recordObservation(plan, outcome.message, signal) : void 0;
73319
+ const governedOutput = plan.kind === "governed" ? await bridge.recordGovernedOutput(plan, outcome.message, durationMs, signal) : void 0;
73320
+ return {
73321
+ ...outcome,
73322
+ ...buildObservedResultMetadata(plan, observed ?? governedOutput)
73323
+ };
73324
+ }
73325
+ function hasReusableToolResultState(cacheKey, cache4, pending, policyCheckedKeys, pendingSafetyChecks) {
73326
+ return cache4.has(cacheKey) || pending.has(cacheKey) || policyCheckedKeys.has(cacheKey) || (pendingSafetyChecks.get(cacheKey) ?? 0) > 0;
73327
+ }
73328
+ function incrementPendingReusableToolSafetyCheck(cacheKey, pendingSafetyChecks) {
73329
+ if (!cacheKey) {
73330
+ return;
73331
+ }
73332
+ pendingSafetyChecks.set(cacheKey, (pendingSafetyChecks.get(cacheKey) ?? 0) + 1);
73333
+ }
73334
+ function decrementPendingReusableToolSafetyCheck(cacheKey, pendingSafetyChecks) {
73335
+ if (!cacheKey) {
73336
+ return;
73337
+ }
73338
+ const nextCount = (pendingSafetyChecks.get(cacheKey) ?? 0) - 1;
73339
+ if (nextCount <= 0) {
73340
+ pendingSafetyChecks.delete(cacheKey);
73341
+ return;
73342
+ }
73343
+ pendingSafetyChecks.set(cacheKey, nextCount);
73344
+ }
73345
+ function clearReusableToolResultState(cache4, pending, policyCheckedKeys, pendingSafetyChecks, cacheGeneration) {
73346
+ cache4.clear();
73347
+ pending.clear();
73348
+ policyCheckedKeys.clear();
73349
+ pendingSafetyChecks.clear();
73350
+ cacheGeneration.value += 1;
73351
+ }
73352
+ function clearRunScopedReusableToolResultState(cache4, pending, policyCheckedKeys, pendingSafetyChecks, cacheGeneration) {
73353
+ let cleared = false;
73354
+ for (const key of cache4.keys()) {
73355
+ if (key.startsWith(RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX)) {
73356
+ cache4.delete(key);
73357
+ cleared = true;
73358
+ }
73359
+ }
73360
+ for (const key of pending.keys()) {
73361
+ if (key.startsWith(RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX)) {
73362
+ pending.delete(key);
73363
+ cleared = true;
73364
+ }
73365
+ }
73366
+ for (const key of policyCheckedKeys) {
73367
+ if (key.startsWith(RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX)) {
73368
+ policyCheckedKeys.delete(key);
73369
+ cleared = true;
73370
+ }
73371
+ }
73372
+ for (const key of pendingSafetyChecks.keys()) {
73373
+ if (key.startsWith(RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX)) {
73374
+ pendingSafetyChecks.delete(key);
73375
+ cleared = true;
73376
+ }
73377
+ }
73378
+ if (cleared) {
73379
+ cacheGeneration.value += 1;
73380
+ }
73381
+ }
73382
+ function invalidateReusableToolResultsAfterMutation(toolCall, tools, cache4, pending, policyCheckedKeys, pendingSafetyChecks, cacheGeneration) {
73383
+ if (isReadOnlyToolCallForCacheInvalidation(toolCall, tools)) {
73384
+ return;
73385
+ }
73386
+ clearReusableToolResultState(cache4, pending, policyCheckedKeys, pendingSafetyChecks, cacheGeneration);
73387
+ }
73388
+ function hasPendingMutatingToolExecution(pendingExecutions, tools) {
73389
+ return pendingExecutions.some((execution) => !isReadOnlyToolCallForCacheInvalidation(execution.toolCall, tools));
73390
+ }
73391
+ function trackReusableToolResult(cacheKey, executionPromise, cache4, pending, policyCheckedKeys, cacheGeneration) {
73392
+ const trackedGeneration = cacheGeneration?.value;
73393
+ const trackedPromise = executionPromise.then((outcome) => {
73394
+ if (!outcome.isError && outcome.message.isError !== true && (cacheGeneration === void 0 || cacheGeneration.value === trackedGeneration)) {
73395
+ cache4.set(cacheKey, {
73396
+ message: cloneToolResultForCache(outcome.message)
73397
+ });
73398
+ } else {
73399
+ policyCheckedKeys?.delete(cacheKey);
73400
+ }
73401
+ return outcome;
73402
+ }).catch((error) => {
73403
+ policyCheckedKeys?.delete(cacheKey);
73404
+ throw error;
73405
+ }).finally(() => {
73406
+ if (pending.get(cacheKey) === trackedPromise) {
73407
+ pending.delete(cacheKey);
73408
+ }
73409
+ });
73410
+ pending.set(cacheKey, trackedPromise);
73411
+ return trackedPromise;
73412
+ }
73413
+ var REUSABLE_TOOL_RESULT_GIT_SNAPSHOT_TIMEOUT_MS = 5e3;
73414
+ var GIT_SNAPSHOT_REUSABLE_TOOL_NAMES;
73415
+ var REPO_PATH_ARGUMENTS_BY_TOOL;
73416
+ var GIT_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX = "git:";
73417
+ var RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX = "run:";
73418
+ var NETWORK_BACKED_REUSABLE_TOOL_DENYLIST;
73419
+ var REQUIRED_REPO_PATH_ARGUMENT_TOOLS;
73420
+ var reusableToolDefinitionIdentities;
73421
+ var reusableToolDefinitionIdentityCounter = 0;
73422
+ var init_reusable_tool_results = __esm2(() => {
73423
+ init_parallel_execution();
73424
+ init_tool_execution_bridge();
73425
+ GIT_SNAPSHOT_REUSABLE_TOOL_NAMES = /* @__PURE__ */ new Set([
73426
+ "read",
73427
+ "ls",
73428
+ "list",
73429
+ "glob",
73430
+ "find",
73431
+ "grep",
73432
+ "search",
73433
+ "parallel_ripgrep",
73434
+ "diff",
73435
+ "status"
73436
+ ]);
73437
+ REPO_PATH_ARGUMENTS_BY_TOOL = /* @__PURE__ */ new Map([
73438
+ ["read", ["path", "file_path"]],
73439
+ ["ls", ["path", "dir", "directory"]],
73440
+ ["list", ["path", "dir", "directory"]],
73441
+ ["glob", ["path", "cwd", "root", "glob"]],
73442
+ ["find", ["path", "cwd", "root", "glob"]],
73443
+ ["grep", ["path", "paths", "glob"]],
73444
+ ["search", ["path", "paths", "glob"]],
73445
+ ["parallel_ripgrep", ["path", "paths", "glob"]],
73446
+ ["diff", ["path", "paths", "cwd"]],
73447
+ ["status", ["path", "paths", "cwd"]]
73448
+ ]);
73449
+ NETWORK_BACKED_REUSABLE_TOOL_DENYLIST = /* @__PURE__ */ new Set(["extract_document"]);
73450
+ REQUIRED_REPO_PATH_ARGUMENT_TOOLS = /* @__PURE__ */ new Set(["read", "ls", "list"]);
73451
+ reusableToolDefinitionIdentities = /* @__PURE__ */ new WeakMap();
73452
+ });
73040
73453
  function isComposerError(error) {
73041
73454
  return error instanceof ComposerError;
73042
73455
  }
@@ -80904,7 +81317,7 @@ function substituteFileRefs(text2, configDir) {
80904
81317
  filePath = join25(configDir, filePath);
80905
81318
  }
80906
81319
  try {
80907
- const fileContent = readFileSync16(filePath, "utf-8").trim();
81320
+ const fileContent = readFileSync17(filePath, "utf-8").trim();
80908
81321
  const escaped = JSON.stringify(fileContent).slice(1, -1);
80909
81322
  processedLine = processedLine.replace(match[0], escaped);
80910
81323
  } catch (error) {
@@ -81051,7 +81464,7 @@ function readJsonFile(filePath) {
81051
81464
  if (cached && cached.mtimeMs === stats2.mtimeMs) {
81052
81465
  return cached.data;
81053
81466
  }
81054
- const data = readFileSync17(filePath, "utf-8");
81467
+ const data = readFileSync18(filePath, "utf-8");
81055
81468
  fileSnapshots.set(filePath, { mtimeMs: stats2.mtimeMs, data });
81056
81469
  return data;
81057
81470
  } catch {
@@ -81475,7 +81888,7 @@ function validateConfig3() {
81475
81888
  }
81476
81889
  result2.summary.configFiles.push(path23);
81477
81890
  try {
81478
- const raw = readFileSync18(path23, "utf-8");
81891
+ const raw = readFileSync19(path23, "utf-8");
81479
81892
  const fileMatches = [...raw.matchAll(/\{file:([^}]+)\}/g)];
81480
81893
  for (const match of fileMatches) {
81481
81894
  const matchedPath = match[1];
@@ -81569,7 +81982,7 @@ function inspectConfig() {
81569
81982
  for (const path23 of paths) {
81570
81983
  if (!existsSync24(path23))
81571
81984
  continue;
81572
- const raw = readFileSync18(path23, "utf-8");
81985
+ const raw = readFileSync19(path23, "utf-8");
81573
81986
  const fileMatches = [...raw.matchAll(/\{file:([^}]+)\}/g)];
81574
81987
  for (const match of fileMatches) {
81575
81988
  const matchedPath = match[1];
@@ -81598,7 +82011,7 @@ function inspectConfig() {
81598
82011
  for (const path23 of paths) {
81599
82012
  if (!existsSync24(path23))
81600
82013
  continue;
81601
- const raw = readFileSync18(path23, "utf-8");
82014
+ const raw = readFileSync19(path23, "utf-8");
81602
82015
  const envMatches = [...raw.matchAll(/\{env:([^}]+)\}/g)];
81603
82016
  for (const match of envMatches) {
81604
82017
  const envVar = match[1];
@@ -83317,369 +83730,6 @@ async function waitForNextExecutionOrUpdate(pendingExecutions, updateQueue) {
83317
83730
  }
83318
83731
  return next;
83319
83732
  }
83320
- function hashReusableToolResultSnapshot(value) {
83321
- return createHash13("sha256").update(value).digest("hex");
83322
- }
83323
- function readGitSnapshotBuffer(cwd, args) {
83324
- return execFileSync2("git", args, {
83325
- cwd,
83326
- stdio: ["ignore", "pipe", "ignore"],
83327
- timeout: REUSABLE_TOOL_RESULT_GIT_SNAPSHOT_TIMEOUT_MS
83328
- });
83329
- }
83330
- function readGitSnapshotPart(cwd, args) {
83331
- return readGitSnapshotBuffer(cwd, args).toString("utf8").trim();
83332
- }
83333
- function hashGitSnapshotPart(cwd, args) {
83334
- return hashReusableToolResultSnapshot(readGitSnapshotBuffer(cwd, args));
83335
- }
83336
- function hashUntrackedGitFiles(root) {
83337
- const files = readGitSnapshotBuffer(root, [
83338
- "ls-files",
83339
- "--others",
83340
- "--exclude-standard",
83341
- "-z"
83342
- ]).toString("utf8").split("\0").filter(Boolean).sort();
83343
- const hash = createHash13("sha256");
83344
- for (const file of files) {
83345
- hash.update(file);
83346
- hash.update("\0");
83347
- hash.update(readFileSync19(resolvePath(root, file)));
83348
- hash.update("\0");
83349
- }
83350
- return hash.digest("hex");
83351
- }
83352
- function hasDirtyGitSubmodules(root) {
83353
- try {
83354
- return readGitSnapshotPart(root, [
83355
- "submodule",
83356
- "foreach",
83357
- "--recursive",
83358
- "--quiet",
83359
- "git status --porcelain=v1 --untracked-files=all"
83360
- ]).length > 0;
83361
- } catch {
83362
- return true;
83363
- }
83364
- }
83365
- function computeReusableToolResultSnapshot(cwd) {
83366
- try {
83367
- const root = readGitSnapshotPart(cwd, ["rev-parse", "--show-toplevel"]);
83368
- const head = readGitSnapshotPart(cwd, ["rev-parse", "--verify", "HEAD"]);
83369
- const status = readGitSnapshotPart(root, [
83370
- "status",
83371
- "--porcelain=v1",
83372
- "--untracked-files=all"
83373
- ]);
83374
- if (hasDirtyGitSubmodules(root)) {
83375
- return;
83376
- }
83377
- const unstagedDiff = hashGitSnapshotPart(root, [
83378
- "diff",
83379
- "--no-ext-diff",
83380
- "--binary"
83381
- ]);
83382
- const stagedDiff = hashGitSnapshotPart(root, [
83383
- "diff",
83384
- "--cached",
83385
- "--no-ext-diff",
83386
- "--binary"
83387
- ]);
83388
- const untracked = hashUntrackedGitFiles(root);
83389
- return `git:${hashReusableToolResultSnapshot(`${root}
83390
- ${head}
83391
- ${status}
83392
- ${unstagedDiff}
83393
- ${stagedDiff}
83394
- ${untracked}`)}`;
83395
- } catch {
83396
- return;
83397
- }
83398
- }
83399
- function collectStringValues(value) {
83400
- if (typeof value === "string") {
83401
- return [value];
83402
- }
83403
- if (Array.isArray(value)) {
83404
- return value.flatMap((item) => collectStringValues(item));
83405
- }
83406
- return [];
83407
- }
83408
- function isRepoRelativePathArgument(value) {
83409
- const trimmed = value.trim();
83410
- if (trimmed.length === 0) {
83411
- return false;
83412
- }
83413
- if (trimmed.startsWith("/") || trimmed.startsWith("~") || trimmed.startsWith("\\\\") || /^[A-Za-z]:[\\/]/.test(trimmed)) {
83414
- return false;
83415
- }
83416
- return !trimmed.split(/[\\/]+/).includes("..");
83417
- }
83418
- function isGitIgnoredRepoPath(cwd, repoPath) {
83419
- try {
83420
- readGitSnapshotPart(cwd, ["check-ignore", "--quiet", "--", repoPath]);
83421
- return true;
83422
- } catch (error) {
83423
- if (typeof error === "object" && error !== null && "status" in error && error.status === 1) {
83424
- return false;
83425
- }
83426
- return true;
83427
- }
83428
- }
83429
- function isToolCallIncludingIgnoredPaths(toolCall) {
83430
- const toolName = toolCall.name.toLowerCase();
83431
- const args = toolCall.arguments;
83432
- if (!args || typeof args !== "object" || Array.isArray(args)) {
83433
- return false;
83434
- }
83435
- const record = args;
83436
- if (toolName === "status") {
83437
- return record.includeIgnored === true || record.include_ignored === true;
83438
- }
83439
- if (toolName === "search" || toolName === "parallel_ripgrep") {
83440
- return record.useGitIgnore === false || record.use_git_ignore === false;
83441
- }
83442
- return false;
83443
- }
83444
- function hasRepoScopedReusableArguments(toolCall, cwd) {
83445
- const toolName = toolCall.name.toLowerCase();
83446
- if (isToolCallIncludingIgnoredPaths(toolCall)) {
83447
- return false;
83448
- }
83449
- const argumentNames = REPO_PATH_ARGUMENTS_BY_TOOL.get(toolName) ?? [];
83450
- if (argumentNames.length === 0) {
83451
- return true;
83452
- }
83453
- const args = toolCall.arguments;
83454
- if (!args || typeof args !== "object" || Array.isArray(args)) {
83455
- return !REQUIRED_REPO_PATH_ARGUMENT_TOOLS.has(toolName);
83456
- }
83457
- const pathValues = argumentNames.flatMap((name) => collectStringValues(args[name]));
83458
- if (pathValues.length === 0 && REQUIRED_REPO_PATH_ARGUMENT_TOOLS.has(toolName)) {
83459
- return false;
83460
- }
83461
- return pathValues.every((pathValue) => isRepoRelativePathArgument(pathValue) && !isGitIgnoredRepoPath(cwd, pathValue));
83462
- }
83463
- function isGitSnapshotReusableToolCall(tool, toolCall, cwd) {
83464
- if (tool.source !== void 0 || tool.annotations?.openWorldHint === true || tool.executionLocation === "client") {
83465
- return false;
83466
- }
83467
- if (!GIT_SNAPSHOT_REUSABLE_TOOL_NAMES.has(tool.name.toLowerCase())) {
83468
- return false;
83469
- }
83470
- if (!isReadOnlyTool(tool.name, tool.annotations, tool.source)) {
83471
- return false;
83472
- }
83473
- return hasRepoScopedReusableArguments(toolCall, cwd);
83474
- }
83475
- function getReusableToolDefinitionIdentity(value) {
83476
- const existing = reusableToolDefinitionIdentities.get(value);
83477
- if (existing !== void 0) {
83478
- return existing;
83479
- }
83480
- reusableToolDefinitionIdentityCounter += 1;
83481
- reusableToolDefinitionIdentities.set(value, reusableToolDefinitionIdentityCounter);
83482
- return reusableToolDefinitionIdentityCounter;
83483
- }
83484
- function getReusableToolFunctionIdentity(value) {
83485
- return typeof value === "function" ? getReusableToolDefinitionIdentity(value) : void 0;
83486
- }
83487
- function getReusableToolRegistrySignature(tools) {
83488
- return stableStringify(tools.map((tool) => ({
83489
- allowedCallers: tool.allowedCallers,
83490
- annotations: tool.annotations,
83491
- deferApiDefinition: tool.deferApiDefinition,
83492
- description: tool.description,
83493
- executeIdentity: getReusableToolFunctionIdentity(tool.execute),
83494
- executionLocation: tool.executionLocation,
83495
- getActivityDescriptionIdentity: getReusableToolFunctionIdentity(tool.getActivityDescription),
83496
- getDisplayNameIdentity: getReusableToolFunctionIdentity(tool.getDisplayName),
83497
- getToolUseSummaryIdentity: getReusableToolFunctionIdentity(tool.getToolUseSummary),
83498
- inputExamples: tool.inputExamples,
83499
- label: tool.label,
83500
- maxRetries: tool.maxRetries,
83501
- name: tool.name,
83502
- parameters: tool.parameters,
83503
- retryDelayMs: tool.retryDelayMs,
83504
- shouldRetryIdentity: getReusableToolFunctionIdentity(tool.shouldRetry),
83505
- source: tool.source,
83506
- toolIdentity: getReusableToolDefinitionIdentity(tool),
83507
- toolType: tool.toolType
83508
- })));
83509
- }
83510
- function createToolMetadataCache(tools, reusableToolResultCwd = process.cwd()) {
83511
- const definitions = new Map(tools.map((tool) => [tool.name, tool]));
83512
- return {
83513
- definitions,
83514
- reusableToolResultCwd,
83515
- lookupCount: 0,
83516
- get(toolName) {
83517
- this.lookupCount += 1;
83518
- return definitions.get(toolName);
83519
- }
83520
- };
83521
- }
83522
- function getToolDefinition(lookup2, toolName) {
83523
- if ("get" in lookup2 && !Array.isArray(lookup2)) {
83524
- return lookup2.get(toolName);
83525
- }
83526
- return lookup2.find((candidate) => candidate.name === toolName);
83527
- }
83528
- function getReusableToolResultCacheKey(toolCall, tools) {
83529
- const tool = getToolDefinition(tools, toolCall.name);
83530
- const cwd = "reusableToolResultCwd" in tools ? tools.reusableToolResultCwd : process.cwd();
83531
- if (!tool || tool.annotations?.destructiveHint === true) {
83532
- return;
83533
- }
83534
- if (!isReadOnlyTool(tool.name, tool.annotations, tool.source)) {
83535
- return;
83536
- }
83537
- const toolName = tool.name.toLowerCase();
83538
- const cacheKey = `${toolCall.name}:${stableStringify(toolCall.arguments)}`;
83539
- if (NETWORK_BACKED_REUSABLE_TOOL_DENYLIST.has(toolName)) {
83540
- return;
83541
- }
83542
- if (isGitSnapshotReusableToolCall(tool, toolCall, cwd)) {
83543
- return `${GIT_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX}${cacheKey}`;
83544
- }
83545
- if (tool.source !== void 0 || GIT_SNAPSHOT_REUSABLE_TOOL_NAMES.has(toolName) || tool.annotations?.openWorldHint === true || tool.executionLocation === "client") {
83546
- return;
83547
- }
83548
- return `${RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX}${cacheKey}`;
83549
- }
83550
- function isReadOnlyToolCallForCacheInvalidation(toolCall, tools) {
83551
- const tool = getToolDefinition(tools, toolCall.name);
83552
- return tool ? isReadOnlyTool(tool.name, tool.annotations, tool.source) : false;
83553
- }
83554
- function cloneToolResultForCache(message) {
83555
- return {
83556
- ...message,
83557
- content: message.content.map((item) => ({ ...item }))
83558
- };
83559
- }
83560
- function cloneToolOutcomeForCall(outcome, toolCall, timestamp3) {
83561
- return {
83562
- message: {
83563
- ...outcome.message,
83564
- toolCallId: toolCall.id,
83565
- toolName: toolCall.name,
83566
- content: outcome.message.content.map((item) => ({ ...item })),
83567
- timestamp: timestamp3
83568
- },
83569
- isError: outcome.isError
83570
- };
83571
- }
83572
- function resolvePlatformToolExecutionBridge(option) {
83573
- if (option === false) {
83574
- return;
83575
- }
83576
- return option ?? getDefaultPlatformToolExecutionBridge();
83577
- }
83578
- async function recordReusableToolExecutionBridgeOutput({
83579
- bridge,
83580
- plan,
83581
- outcome,
83582
- durationMs,
83583
- signal
83584
- }) {
83585
- if (!bridge || !plan) {
83586
- return outcome;
83587
- }
83588
- const observed = plan.kind === "observe" ? await bridge.recordObservation(plan, outcome.message, signal) : void 0;
83589
- const governedOutput = plan.kind === "governed" ? await bridge.recordGovernedOutput(plan, outcome.message, durationMs, signal) : void 0;
83590
- return {
83591
- ...outcome,
83592
- ...buildObservedResultMetadata(plan, observed ?? governedOutput)
83593
- };
83594
- }
83595
- function hasReusableToolResultState(cacheKey, cache4, pending, policyCheckedKeys, pendingSafetyChecks) {
83596
- return cache4.has(cacheKey) || pending.has(cacheKey) || policyCheckedKeys.has(cacheKey) || (pendingSafetyChecks.get(cacheKey) ?? 0) > 0;
83597
- }
83598
- function incrementPendingReusableToolSafetyCheck(cacheKey, pendingSafetyChecks) {
83599
- if (!cacheKey) {
83600
- return;
83601
- }
83602
- pendingSafetyChecks.set(cacheKey, (pendingSafetyChecks.get(cacheKey) ?? 0) + 1);
83603
- }
83604
- function decrementPendingReusableToolSafetyCheck(cacheKey, pendingSafetyChecks) {
83605
- if (!cacheKey) {
83606
- return;
83607
- }
83608
- const nextCount = (pendingSafetyChecks.get(cacheKey) ?? 0) - 1;
83609
- if (nextCount <= 0) {
83610
- pendingSafetyChecks.delete(cacheKey);
83611
- return;
83612
- }
83613
- pendingSafetyChecks.set(cacheKey, nextCount);
83614
- }
83615
- function clearReusableToolResultState(cache4, pending, policyCheckedKeys, pendingSafetyChecks, cacheGeneration) {
83616
- cache4.clear();
83617
- pending.clear();
83618
- policyCheckedKeys.clear();
83619
- pendingSafetyChecks.clear();
83620
- cacheGeneration.value += 1;
83621
- }
83622
- function clearRunScopedReusableToolResultState(cache4, pending, policyCheckedKeys, pendingSafetyChecks, cacheGeneration) {
83623
- let cleared = false;
83624
- for (const key of cache4.keys()) {
83625
- if (key.startsWith(RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX)) {
83626
- cache4.delete(key);
83627
- cleared = true;
83628
- }
83629
- }
83630
- for (const key of pending.keys()) {
83631
- if (key.startsWith(RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX)) {
83632
- pending.delete(key);
83633
- cleared = true;
83634
- }
83635
- }
83636
- for (const key of policyCheckedKeys) {
83637
- if (key.startsWith(RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX)) {
83638
- policyCheckedKeys.delete(key);
83639
- cleared = true;
83640
- }
83641
- }
83642
- for (const key of pendingSafetyChecks.keys()) {
83643
- if (key.startsWith(RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX)) {
83644
- pendingSafetyChecks.delete(key);
83645
- cleared = true;
83646
- }
83647
- }
83648
- if (cleared) {
83649
- cacheGeneration.value += 1;
83650
- }
83651
- }
83652
- function invalidateReusableToolResultsAfterMutation(toolCall, tools, cache4, pending, policyCheckedKeys, pendingSafetyChecks, cacheGeneration) {
83653
- if (isReadOnlyToolCallForCacheInvalidation(toolCall, tools)) {
83654
- return;
83655
- }
83656
- clearReusableToolResultState(cache4, pending, policyCheckedKeys, pendingSafetyChecks, cacheGeneration);
83657
- }
83658
- function hasPendingMutatingToolExecution(pendingExecutions, tools) {
83659
- return pendingExecutions.some((execution) => !isReadOnlyToolCallForCacheInvalidation(execution.toolCall, tools));
83660
- }
83661
- function trackReusableToolResult(cacheKey, executionPromise, cache4, pending, policyCheckedKeys, cacheGeneration) {
83662
- const trackedGeneration = cacheGeneration?.value;
83663
- const trackedPromise = executionPromise.then((outcome) => {
83664
- if (!outcome.isError && outcome.message.isError !== true && (cacheGeneration === void 0 || cacheGeneration.value === trackedGeneration)) {
83665
- cache4.set(cacheKey, {
83666
- message: cloneToolResultForCache(outcome.message)
83667
- });
83668
- } else {
83669
- policyCheckedKeys?.delete(cacheKey);
83670
- }
83671
- return outcome;
83672
- }).catch((error) => {
83673
- policyCheckedKeys?.delete(cacheKey);
83674
- throw error;
83675
- }).finally(() => {
83676
- if (pending.get(cacheKey) === trackedPromise) {
83677
- pending.delete(cacheKey);
83678
- }
83679
- });
83680
- pending.set(cacheKey, trackedPromise);
83681
- return trackedPromise;
83682
- }
83683
83733
  var AgentEventQueue = class {
83684
83734
  events = [];
83685
83735
  pending;
@@ -85289,15 +85339,6 @@ var ProviderTransport = class _ProviderTransport {
85289
85339
  }
85290
85340
  };
85291
85341
  var logger69;
85292
- var REUSABLE_TOOL_RESULT_GIT_SNAPSHOT_TIMEOUT_MS = 5e3;
85293
- var GIT_SNAPSHOT_REUSABLE_TOOL_NAMES;
85294
- var REPO_PATH_ARGUMENTS_BY_TOOL;
85295
- var GIT_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX = "git:";
85296
- var RUN_SCOPED_REUSABLE_TOOL_RESULT_KEY_PREFIX = "run:";
85297
- var NETWORK_BACKED_REUSABLE_TOOL_DENYLIST;
85298
- var REQUIRED_REPO_PATH_ARGUMENT_TOOLS;
85299
- var reusableToolDefinitionIdentities;
85300
- var reusableToolDefinitionIdentityCounter = 0;
85301
85342
  var init_transport = __esm2(() => {
85302
85343
  init_env_vars();
85303
85344
  init_hooks();
@@ -85316,38 +85357,11 @@ var init_transport = __esm2(() => {
85316
85357
  init_cost_tracker();
85317
85358
  init_training();
85318
85359
  init_keys();
85319
- init_tool_execution_bridge();
85360
+ init_reusable_tool_results();
85320
85361
  init_tool_execution();
85321
85362
  init_tool_safety_pipeline();
85322
85363
  init_transport_utils();
85323
85364
  logger69 = createLogger("transport");
85324
- GIT_SNAPSHOT_REUSABLE_TOOL_NAMES = /* @__PURE__ */ new Set([
85325
- "read",
85326
- "ls",
85327
- "list",
85328
- "glob",
85329
- "find",
85330
- "grep",
85331
- "search",
85332
- "parallel_ripgrep",
85333
- "diff",
85334
- "status"
85335
- ]);
85336
- REPO_PATH_ARGUMENTS_BY_TOOL = /* @__PURE__ */ new Map([
85337
- ["read", ["path", "file_path"]],
85338
- ["ls", ["path", "dir", "directory"]],
85339
- ["list", ["path", "dir", "directory"]],
85340
- ["glob", ["path", "cwd", "root", "glob"]],
85341
- ["find", ["path", "cwd", "root", "glob"]],
85342
- ["grep", ["path", "paths", "glob"]],
85343
- ["search", ["path", "paths", "glob"]],
85344
- ["parallel_ripgrep", ["path", "paths", "glob"]],
85345
- ["diff", ["path", "paths", "cwd"]],
85346
- ["status", ["path", "paths", "cwd"]]
85347
- ]);
85348
- NETWORK_BACKED_REUSABLE_TOOL_DENYLIST = /* @__PURE__ */ new Set(["extract_document"]);
85349
- REQUIRED_REPO_PATH_ARGUMENT_TOOLS = /* @__PURE__ */ new Set(["read", "ls", "list"]);
85350
- reusableToolDefinitionIdentities = /* @__PURE__ */ new WeakMap();
85351
85365
  });
85352
85366
  function StringEnum(values, options) {
85353
85367
  const enumValues = Array.from(values);
@@ -160221,6 +160235,15 @@ var init_ripgrep_utils = __esm2(() => {
160221
160235
  }), { minItems: 1 })
160222
160236
  ]));
160223
160237
  });
160238
+ function shellQuoteArg(value) {
160239
+ if (/^[A-Za-z0-9_/:=.,@%+-]+$/.test(value)) {
160240
+ return value;
160241
+ }
160242
+ return `'${value.replace(/'/g, "'\\''")}'`;
160243
+ }
160244
+ function formatRipgrepCommand(args) {
160245
+ return ["rg", ...args].map(shellQuoteArg).join(" ");
160246
+ }
160224
160247
  function mergeRanges(ranges) {
160225
160248
  const sorted = [...ranges].sort((a, b) => a.start - b.start);
160226
160249
  const merged = [];
@@ -160428,7 +160451,7 @@ var init_parallel_ripgrep = __esm2(() => {
160428
160451
  let truncatedByBytes = false;
160429
160452
  const ripgrepCalls = patterns.map(async (pattern) => {
160430
160453
  const args = [...baseArgs, "--", pattern, ...pathArgs];
160431
- commands.push(["rg", ...args].join(" "));
160454
+ commands.push(formatRipgrepCommand(args));
160432
160455
  const result2 = await runRipgrep(args, signal, commandCwd);
160433
160456
  truncatedByBytes ||= result2.truncated;
160434
160457
  return { pattern, result: result2 };
@@ -160438,7 +160461,7 @@ var init_parallel_ripgrep = __esm2(() => {
160438
160461
  results = await Promise.all(ripgrepCalls);
160439
160462
  } catch (error) {
160440
160463
  const reason = error instanceof Error ? error.message : `Unknown error: ${String(error)}`;
160441
- return respond.text(`ripgrep failed
160464
+ return respond.error(`ripgrep failed
160442
160465
 
160443
160466
  ${reason}`).detail({
160444
160467
  commands,
@@ -171992,6 +172015,209 @@ var init_runtime_events = __esm2(() => {
171992
172015
  logger161 = createLogger("agent:swarm:runtime-events");
171993
172016
  runtimeEventHandlers = /* @__PURE__ */ new Set();
171994
172017
  });
172018
+ function createConnectionId() {
172019
+ return `conn_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
172020
+ }
172021
+ function createSubscriptionId() {
172022
+ return `sub_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
172023
+ }
172024
+ var HeadlessSubscriberMailbox = class {
172025
+ id;
172026
+ role;
172027
+ explicit;
172028
+ connectionId;
172029
+ optOutNotifications;
172030
+ listeners = /* @__PURE__ */ new Set();
172031
+ queue = [];
172032
+ queuedReset = null;
172033
+ detachedAt;
172034
+ attached = false;
172035
+ allowRawAgentEvents;
172036
+ constructor(id, role, explicit, connectionId, optOutNotifications = [], allowRawAgentEvents = false) {
172037
+ this.id = id;
172038
+ this.role = role;
172039
+ this.explicit = explicit;
172040
+ this.connectionId = connectionId;
172041
+ this.optOutNotifications = optOutNotifications;
172042
+ this.detachedAt = explicit ? Date.now() : null;
172043
+ this.allowRawAgentEvents = allowRawAgentEvents;
172044
+ }
172045
+ onAvailable(listener) {
172046
+ this.listeners.add(listener);
172047
+ return () => {
172048
+ this.listeners.delete(listener);
172049
+ };
172050
+ }
172051
+ enqueue(envelope, createReset) {
172052
+ if (this.shouldFilterEnvelope(envelope)) {
172053
+ return;
172054
+ }
172055
+ this.queue.push(envelope);
172056
+ if (this.queue.length > MAX_SUBSCRIBER_MAILBOX_EVENTS) {
172057
+ this.queue.length = 0;
172058
+ this.queuedReset = createReset("lagged");
172059
+ }
172060
+ this.emit();
172061
+ }
172062
+ next() {
172063
+ const next = this.queuedReset ?? this.queue.shift() ?? null;
172064
+ if (next?.type === "reset") {
172065
+ this.queuedReset = null;
172066
+ }
172067
+ return next;
172068
+ }
172069
+ attach() {
172070
+ this.attached = true;
172071
+ this.detachedAt = null;
172072
+ this.emit();
172073
+ }
172074
+ detach() {
172075
+ this.attached = false;
172076
+ this.detachedAt = Date.now();
172077
+ }
172078
+ touch() {
172079
+ if (this.explicit && !this.attached) {
172080
+ this.detachedAt = Date.now();
172081
+ }
172082
+ }
172083
+ isExpired(now2 = Date.now()) {
172084
+ return this.explicit && !this.attached && this.detachedAt !== null && now2 - this.detachedAt > MAX_SUBSCRIPTION_IDLE_MS;
172085
+ }
172086
+ isAttached() {
172087
+ return this.attached;
172088
+ }
172089
+ allowsRawAgentEvents() {
172090
+ return this.allowRawAgentEvents;
172091
+ }
172092
+ setAllowRawAgentEvents(value) {
172093
+ this.allowRawAgentEvents = value;
172094
+ }
172095
+ emit() {
172096
+ for (const listener of this.listeners) {
172097
+ listener();
172098
+ }
172099
+ }
172100
+ shouldFilterEnvelope(envelope) {
172101
+ if (envelope.type === "heartbeat") {
172102
+ return this.optOutNotifications.includes("heartbeat");
172103
+ }
172104
+ if (envelope.type !== "message") {
172105
+ return false;
172106
+ }
172107
+ if (envelope.message.type === "raw_agent_event" && !this.allowRawAgentEvents) {
172108
+ return true;
172109
+ }
172110
+ if (this.optOutNotifications.length === 0) {
172111
+ return false;
172112
+ }
172113
+ switch (envelope.message.type) {
172114
+ case "status":
172115
+ return this.optOutNotifications.includes("status");
172116
+ case "connection_info":
172117
+ return this.optOutNotifications.includes("connection_info");
172118
+ case "compaction":
172119
+ return this.optOutNotifications.includes("compaction");
172120
+ default:
172121
+ return false;
172122
+ }
172123
+ }
172124
+ };
172125
+ var HeadlessRuntimeBroker = class {
172126
+ nextCursor = 1;
172127
+ listeners = /* @__PURE__ */ new Set();
172128
+ events = [];
172129
+ publishEnvelope(envelope) {
172130
+ assertHeadlessRuntimeStreamEnvelope(envelope, "headless runtime stream envelope");
172131
+ this.events.push(envelope);
172132
+ while (this.events.length > MAX_BUFFERED_EVENTS) {
172133
+ this.events.shift();
172134
+ }
172135
+ for (const listener of this.listeners) {
172136
+ listener(envelope);
172137
+ }
172138
+ return envelope;
172139
+ }
172140
+ publish(message) {
172141
+ const envelope = this.createMessageEnvelope(message);
172142
+ return this.publishEnvelope(envelope);
172143
+ }
172144
+ createPrivateMessage(message) {
172145
+ return this.createMessageEnvelope(message);
172146
+ }
172147
+ createMessageEnvelope(message) {
172148
+ assertHeadlessFromAgentMessage2(message, "headless runtime message");
172149
+ const envelope = {
172150
+ type: "message",
172151
+ cursor: this.nextCursor++,
172152
+ message
172153
+ };
172154
+ return envelope;
172155
+ }
172156
+ publishSnapshot(createSnapshot) {
172157
+ const cursor = this.nextCursor++;
172158
+ const envelope = {
172159
+ type: "snapshot",
172160
+ snapshot: createSnapshot(cursor)
172161
+ };
172162
+ return this.publishEnvelope(envelope);
172163
+ }
172164
+ currentCursor() {
172165
+ return this.nextCursor - 1;
172166
+ }
172167
+ restoreFromSnapshot(snapshot) {
172168
+ const envelope = {
172169
+ type: "reset",
172170
+ reason: "restored_from_snapshot",
172171
+ snapshot
172172
+ };
172173
+ assertHeadlessRuntimeStreamEnvelope(envelope, "headless runtime restore envelope");
172174
+ this.events.length = 0;
172175
+ this.events.push(envelope);
172176
+ this.nextCursor = Math.max(1, snapshot.cursor + 1);
172177
+ }
172178
+ replayFrom(cursor) {
172179
+ if (this.events.length === 0) {
172180
+ return [];
172181
+ }
172182
+ const first = this.events[0];
172183
+ const earliest = this.getEnvelopeCursor(first) ?? this.nextCursor;
172184
+ if (cursor < earliest - 1) {
172185
+ if (first?.type === "reset" && first.reason === "restored_from_snapshot") {
172186
+ return [...this.events];
172187
+ }
172188
+ return null;
172189
+ }
172190
+ return this.events.filter((event) => (this.getEnvelopeCursor(event) ?? 0) > cursor);
172191
+ }
172192
+ subscribe(listener) {
172193
+ this.listeners.add(listener);
172194
+ return () => {
172195
+ this.listeners.delete(listener);
172196
+ };
172197
+ }
172198
+ getEnvelopeCursor(envelope) {
172199
+ if (!envelope) {
172200
+ return;
172201
+ }
172202
+ switch (envelope.type) {
172203
+ case "message":
172204
+ return envelope.cursor;
172205
+ case "heartbeat":
172206
+ return envelope.cursor;
172207
+ case "snapshot":
172208
+ case "reset":
172209
+ return envelope.snapshot.cursor;
172210
+ }
172211
+ }
172212
+ };
172213
+ var MAX_BUFFERED_EVENTS;
172214
+ var MAX_SUBSCRIBER_MAILBOX_EVENTS;
172215
+ var MAX_SUBSCRIPTION_IDLE_MS;
172216
+ var init_broker = __esm2(() => {
172217
+ MAX_BUFFERED_EVENTS = Number.parseInt(process.env.MAESTRO_HEADLESS_RUNTIME_EVENT_BUFFER || "", 10) || 512;
172218
+ MAX_SUBSCRIBER_MAILBOX_EVENTS = Number.parseInt(process.env.MAESTRO_HEADLESS_SUBSCRIBER_QUEUE || "", 10) || 128;
172219
+ MAX_SUBSCRIPTION_IDLE_MS = Number.parseInt(process.env.MAESTRO_HEADLESS_SUBSCRIPTION_IDLE_MS || "", 10) || 30 * 1e3;
172220
+ });
171995
172221
  function jsonRecordArray(value) {
171996
172222
  return Array.isArray(value) ? value.filter((item) => typeof item === "object" && item !== null && !Array.isArray(item)) : [];
171997
172223
  }
@@ -175098,201 +175324,6 @@ async function loadHostedRunnerRestoreManifest(path3) {
175098
175324
  }
175099
175325
  return restore;
175100
175326
  }
175101
- function createConnectionId() {
175102
- return `conn_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
175103
- }
175104
- function createSubscriptionId() {
175105
- return `sub_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
175106
- }
175107
- var HeadlessSubscriberMailbox = class {
175108
- id;
175109
- role;
175110
- explicit;
175111
- connectionId;
175112
- optOutNotifications;
175113
- listeners = /* @__PURE__ */ new Set();
175114
- queue = [];
175115
- queuedReset = null;
175116
- detachedAt;
175117
- attached = false;
175118
- allowRawAgentEvents;
175119
- constructor(id, role, explicit, connectionId, optOutNotifications = [], allowRawAgentEvents = false) {
175120
- this.id = id;
175121
- this.role = role;
175122
- this.explicit = explicit;
175123
- this.connectionId = connectionId;
175124
- this.optOutNotifications = optOutNotifications;
175125
- this.detachedAt = explicit ? Date.now() : null;
175126
- this.allowRawAgentEvents = allowRawAgentEvents;
175127
- }
175128
- onAvailable(listener) {
175129
- this.listeners.add(listener);
175130
- return () => {
175131
- this.listeners.delete(listener);
175132
- };
175133
- }
175134
- enqueue(envelope, createReset) {
175135
- if (this.shouldFilterEnvelope(envelope)) {
175136
- return;
175137
- }
175138
- this.queue.push(envelope);
175139
- if (this.queue.length > MAX_SUBSCRIBER_MAILBOX_EVENTS) {
175140
- this.queue.length = 0;
175141
- this.queuedReset = createReset("lagged");
175142
- }
175143
- this.emit();
175144
- }
175145
- next() {
175146
- const next = this.queuedReset ?? this.queue.shift() ?? null;
175147
- if (next?.type === "reset") {
175148
- this.queuedReset = null;
175149
- }
175150
- return next;
175151
- }
175152
- attach() {
175153
- this.attached = true;
175154
- this.detachedAt = null;
175155
- this.emit();
175156
- }
175157
- detach() {
175158
- this.attached = false;
175159
- this.detachedAt = Date.now();
175160
- }
175161
- touch() {
175162
- if (this.explicit && !this.attached) {
175163
- this.detachedAt = Date.now();
175164
- }
175165
- }
175166
- isExpired(now2 = Date.now()) {
175167
- return this.explicit && !this.attached && this.detachedAt !== null && now2 - this.detachedAt > MAX_SUBSCRIPTION_IDLE_MS;
175168
- }
175169
- isAttached() {
175170
- return this.attached;
175171
- }
175172
- allowsRawAgentEvents() {
175173
- return this.allowRawAgentEvents;
175174
- }
175175
- setAllowRawAgentEvents(value) {
175176
- this.allowRawAgentEvents = value;
175177
- }
175178
- emit() {
175179
- for (const listener of this.listeners) {
175180
- listener();
175181
- }
175182
- }
175183
- shouldFilterEnvelope(envelope) {
175184
- if (envelope.type === "heartbeat") {
175185
- return this.optOutNotifications.includes("heartbeat");
175186
- }
175187
- if (envelope.type !== "message") {
175188
- return false;
175189
- }
175190
- if (envelope.message.type === "raw_agent_event" && !this.allowRawAgentEvents) {
175191
- return true;
175192
- }
175193
- if (this.optOutNotifications.length === 0) {
175194
- return false;
175195
- }
175196
- switch (envelope.message.type) {
175197
- case "status":
175198
- return this.optOutNotifications.includes("status");
175199
- case "connection_info":
175200
- return this.optOutNotifications.includes("connection_info");
175201
- case "compaction":
175202
- return this.optOutNotifications.includes("compaction");
175203
- default:
175204
- return false;
175205
- }
175206
- }
175207
- };
175208
- var HeadlessRuntimeBroker = class {
175209
- nextCursor = 1;
175210
- listeners = /* @__PURE__ */ new Set();
175211
- events = [];
175212
- publishEnvelope(envelope) {
175213
- assertHeadlessRuntimeStreamEnvelope(envelope, "headless runtime stream envelope");
175214
- this.events.push(envelope);
175215
- while (this.events.length > MAX_BUFFERED_EVENTS) {
175216
- this.events.shift();
175217
- }
175218
- for (const listener of this.listeners) {
175219
- listener(envelope);
175220
- }
175221
- return envelope;
175222
- }
175223
- publish(message) {
175224
- const envelope = this.createMessageEnvelope(message);
175225
- return this.publishEnvelope(envelope);
175226
- }
175227
- createPrivateMessage(message) {
175228
- return this.createMessageEnvelope(message);
175229
- }
175230
- createMessageEnvelope(message) {
175231
- assertHeadlessFromAgentMessage2(message, "headless runtime message");
175232
- const envelope = {
175233
- type: "message",
175234
- cursor: this.nextCursor++,
175235
- message
175236
- };
175237
- return envelope;
175238
- }
175239
- publishSnapshot(createSnapshot) {
175240
- const cursor = this.nextCursor++;
175241
- const envelope = {
175242
- type: "snapshot",
175243
- snapshot: createSnapshot(cursor)
175244
- };
175245
- return this.publishEnvelope(envelope);
175246
- }
175247
- currentCursor() {
175248
- return this.nextCursor - 1;
175249
- }
175250
- restoreFromSnapshot(snapshot) {
175251
- const envelope = {
175252
- type: "reset",
175253
- reason: "restored_from_snapshot",
175254
- snapshot
175255
- };
175256
- assertHeadlessRuntimeStreamEnvelope(envelope, "headless runtime restore envelope");
175257
- this.events.length = 0;
175258
- this.events.push(envelope);
175259
- this.nextCursor = Math.max(1, snapshot.cursor + 1);
175260
- }
175261
- replayFrom(cursor) {
175262
- if (this.events.length === 0) {
175263
- return [];
175264
- }
175265
- const first = this.events[0];
175266
- const earliest = this.getEnvelopeCursor(first) ?? this.nextCursor;
175267
- if (cursor < earliest - 1) {
175268
- if (first?.type === "reset" && first.reason === "restored_from_snapshot") {
175269
- return [...this.events];
175270
- }
175271
- return null;
175272
- }
175273
- return this.events.filter((event) => (this.getEnvelopeCursor(event) ?? 0) > cursor);
175274
- }
175275
- subscribe(listener) {
175276
- this.listeners.add(listener);
175277
- return () => {
175278
- this.listeners.delete(listener);
175279
- };
175280
- }
175281
- getEnvelopeCursor(envelope) {
175282
- if (!envelope) {
175283
- return;
175284
- }
175285
- switch (envelope.type) {
175286
- case "message":
175287
- return envelope.cursor;
175288
- case "heartbeat":
175289
- return envelope.cursor;
175290
- case "snapshot":
175291
- case "reset":
175292
- return envelope.snapshot.cursor;
175293
- }
175294
- }
175295
- };
175296
175327
  var HeadlessSessionRuntime = class _HeadlessSessionRuntime {
175297
175328
  translator = new HeadlessProtocolTranslator();
175298
175329
  broker = new HeadlessRuntimeBroker();
@@ -175949,7 +175980,7 @@ var HeadlessSessionRuntime = class _HeadlessSessionRuntime {
175949
175980
  next: () => subscriber.next(),
175950
175981
  onAvailable: (listener) => subscriber.onAvailable(listener),
175951
175982
  enqueue: (envelope) => {
175952
- assertHeadlessRuntimeStreamEnvelope(envelope, "headless attached subscription envelope");
175983
+ assertHeadlessRuntimeStreamEnvelope2(envelope, "headless attached subscription envelope");
175953
175984
  subscriber.enqueue(envelope, (reason) => this.buildResetEnvelope(reason));
175954
175985
  },
175955
175986
  close: () => {
@@ -176079,7 +176110,7 @@ var HeadlessSessionRuntime = class _HeadlessSessionRuntime {
176079
176110
  type: "heartbeat",
176080
176111
  cursor: this.broker.currentCursor()
176081
176112
  };
176082
- assertHeadlessRuntimeStreamEnvelope(envelope, "headless runtime heartbeat envelope");
176113
+ assertHeadlessRuntimeStreamEnvelope2(envelope, "headless runtime heartbeat envelope");
176083
176114
  return envelope;
176084
176115
  }
176085
176116
  heartbeatConnection(input) {
@@ -176434,7 +176465,7 @@ var HeadlessSessionRuntime = class _HeadlessSessionRuntime {
176434
176465
  }
176435
176466
  }
176436
176467
  publish(message) {
176437
- assertHeadlessFromAgentMessage2(message, "headless runtime message");
176468
+ assertHeadlessFromAgentMessage3(message, "headless runtime message");
176438
176469
  if (message.type === "server_request") {
176439
176470
  this.publishedServerRequestIds.add(message.request_id);
176440
176471
  } else if (message.type === "server_request_resolved") {
@@ -176794,9 +176825,6 @@ var HeadlessRuntimeService = class {
176794
176825
  }
176795
176826
  };
176796
176827
  var logger163;
176797
- var MAX_BUFFERED_EVENTS;
176798
- var MAX_SUBSCRIBER_MAILBOX_EVENTS;
176799
- var MAX_SUBSCRIPTION_IDLE_MS;
176800
176828
  var CONNECTION_HEARTBEAT_INTERVAL_MS;
176801
176829
  var MAX_CONNECTION_IDLE_MS;
176802
176830
  var MAX_IDLE_MS;
@@ -176823,13 +176851,11 @@ var init_headless_runtime_service = __esm2(() => {
176823
176851
  init_approval_service();
176824
176852
  init_circuit_breaker2();
176825
176853
  init_client_tools_service();
176854
+ init_broker();
176826
176855
  init_hosted_agent_runtime_progress();
176827
176856
  init_server_request_manager();
176828
176857
  init_tool_retry_service();
176829
176858
  logger163 = createLogger("server:headless-runtime");
176830
- MAX_BUFFERED_EVENTS = Number.parseInt(process.env.MAESTRO_HEADLESS_RUNTIME_EVENT_BUFFER || "", 10) || 512;
176831
- MAX_SUBSCRIBER_MAILBOX_EVENTS = Number.parseInt(process.env.MAESTRO_HEADLESS_SUBSCRIBER_QUEUE || "", 10) || 128;
176832
- MAX_SUBSCRIPTION_IDLE_MS = Number.parseInt(process.env.MAESTRO_HEADLESS_SUBSCRIPTION_IDLE_MS || "", 10) || 30 * 1e3;
176833
176859
  CONNECTION_HEARTBEAT_INTERVAL_MS = Number.parseInt(process.env.MAESTRO_HEADLESS_CONNECTION_HEARTBEAT_INTERVAL_MS || "", 10) || 15 * 1e3;
176834
176860
  MAX_CONNECTION_IDLE_MS = Number.parseInt(process.env.MAESTRO_HEADLESS_CONNECTION_IDLE_MS || "", 10) || CONNECTION_HEARTBEAT_INTERVAL_MS * 3;
176835
176861
  MAX_IDLE_MS = Number.parseInt(process.env.MAESTRO_HEADLESS_RUNTIME_IDLE_MS || "", 10) || 30 * 60 * 1e3;
@@ -196885,6 +196911,59 @@ function isTerminalCandidate(entry2) {
196885
196911
  function runStepStateForEntry(entry2) {
196886
196912
  return entry2.state === "blocked" ? "failed" : entry2.state;
196887
196913
  }
196914
+ function firstEvidenceId2(entry2, kind) {
196915
+ return entry2.evidence.find((anchor) => anchor.kind === kind)?.id;
196916
+ }
196917
+ function evidenceRefForAnchor(anchor) {
196918
+ switch (anchor.kind) {
196919
+ case "timeline_item":
196920
+ return `timeline-item:${anchor.id}`;
196921
+ case "tool_call":
196922
+ return `tool-call:${anchor.id}`;
196923
+ case "tool_execution":
196924
+ return `tool-execution:${anchor.id}`;
196925
+ case "approval_request":
196926
+ return `approval-request:${anchor.id}`;
196927
+ case "pending_request":
196928
+ return `pending-request:${anchor.id}`;
196929
+ case "agent_run":
196930
+ return `agent-run:${anchor.id}`;
196931
+ case "parent_agent_run":
196932
+ return `parent-agent-run:${anchor.id}`;
196933
+ case "child_agent_run":
196934
+ return `child-agent-run:${anchor.id}`;
196935
+ default:
196936
+ return `${anchor.kind}:${anchor.id}`;
196937
+ }
196938
+ }
196939
+ function uniqueStrings3(values) {
196940
+ return values.filter((value, index2) => {
196941
+ return typeof value === "string" && value.length > 0 && values.indexOf(value) === index2;
196942
+ });
196943
+ }
196944
+ function evidenceRefsForEntry(entry2) {
196945
+ return uniqueStrings3([
196946
+ `trajectory-event:${entry2.trajectoryEventId}`,
196947
+ ...entry2.timelineItemId ? [`timeline-item:${entry2.timelineItemId}`] : [],
196948
+ ...entry2.evidence.map(evidenceRefForAnchor)
196949
+ ]);
196950
+ }
196951
+ function workItemPayloadForEntry(sessionId, entry2) {
196952
+ return {
196953
+ maestroSessionId: sessionId,
196954
+ ledgerEntryId: entry2.id,
196955
+ trajectoryEventId: entry2.trajectoryEventId,
196956
+ eventType: entry2.type,
196957
+ phase: entry2.phase,
196958
+ actor: entry2.actor,
196959
+ source: entry2.source,
196960
+ state: entry2.state,
196961
+ ...entry2.timelineItemId ? { timelineItemId: entry2.timelineItemId } : {},
196962
+ ...entry2.toolName ? { toolName: entry2.toolName } : {},
196963
+ ...entry2.summary ? { summary: entry2.summary } : {},
196964
+ ...entry2.relatedIds.length > 0 ? { relatedIds: entry2.relatedIds } : {}
196965
+ };
196966
+ }
196888
196967
  function terminalEntry(entries) {
196889
196968
  const last = entries.at(-1);
196890
196969
  if (!last || !isTerminalState(last.state))
@@ -196944,6 +197023,9 @@ function buildPromotionPlan(runId, sessionId, generatedAt, entries) {
196944
197023
  }
196945
197024
  ];
196946
197025
  for (const entry2 of entries) {
197026
+ const toolExecutionId = firstEvidenceId2(entry2, "tool_execution");
197027
+ const evidenceRefs = evidenceRefsForEntry(entry2);
197028
+ const waitId = entry2.platformShape.waitType ? entry2.id : void 0;
196947
197029
  operations.push({
196948
197030
  operation: "record_run_step",
196949
197031
  id: `promote:${entry2.id}:step`,
@@ -196966,7 +197048,12 @@ function buildPromotionPlan(runId, sessionId, generatedAt, entries) {
196966
197048
  kind: entry2.platformShape.workItemKind,
196967
197049
  state: entry2.state,
196968
197050
  title: entry2.title,
196969
- timestamp: entry2.timestamp
197051
+ timestamp: entry2.timestamp,
197052
+ ...waitId ? { waitId } : {},
197053
+ ...toolExecutionId ? { toolExecutionId } : {},
197054
+ evidenceRefs,
197055
+ completionGate: "maestro_agent_runtime_ledger_recorded",
197056
+ payload: workItemPayloadForEntry(sessionId, entry2)
196970
197057
  }
196971
197058
  });
196972
197059
  if (entry2.platformShape.waitType) {
@@ -197205,6 +197292,23 @@ function buildCoverage(counts, promptContext, contextManifest) {
197205
197292
  mcpContext: contextManifest.mcpServers > 0 || promptContext.mcpServers > 0
197206
197293
  };
197207
197294
  }
197295
+ function buildDurabilitySummary(input) {
197296
+ const sessionFilePresent = typeof input.sessionFile === "string" && input.sessionFile.length > 0;
197297
+ const contextManifestPresent = input.contextManifest.protocolVersion !== void 0;
197298
+ const replayDeterministic = input.agentRuntimeLedger.replay.deterministic;
197299
+ return {
197300
+ reconstructable: sessionFilePresent && input.counts.timelineItems > 0 && replayDeterministic,
197301
+ sessionFilePresent,
197302
+ resumeSummaryPresent: typeof input.session.resumeSummary === "string" && input.session.resumeSummary.trim().length > 0,
197303
+ memoryExtractionHashPresent: typeof input.session.memoryExtractionHash === "string" && input.session.memoryExtractionHash.trim().length > 0,
197304
+ contextManifestPresent,
197305
+ compactionCheckpoints: input.counts.byType["compaction.created"] ?? 0,
197306
+ pendingRequests: input.counts.byType["wait.pending"] ?? 0,
197307
+ agentRuntimeLedgerEntries: input.agentRuntimeLedger.counts.entries,
197308
+ replayDeterministic,
197309
+ promotionIdempotencyKey: input.agentRuntimeLedger.promotion.idempotencyKey
197310
+ };
197311
+ }
197208
197312
  async function buildRunReconstructionReport(sessionId, options = {}) {
197209
197313
  const manager = new SessionManager(false, void 0, {
197210
197314
  sessionDir: options.sessionDir
@@ -197263,6 +197367,12 @@ async function buildRunReconstructionReport(sessionId, options = {}) {
197263
197367
  if (session.summary) {
197264
197368
  sessionReport.summary = session.summary;
197265
197369
  }
197370
+ if (session.resumeSummary) {
197371
+ sessionReport.resumeSummary = session.resumeSummary;
197372
+ }
197373
+ if (session.memoryExtractionHash) {
197374
+ sessionReport.memoryExtractionHash = session.memoryExtractionHash;
197375
+ }
197266
197376
  if (header?.cwd) {
197267
197377
  sessionReport.cwd = header.cwd;
197268
197378
  }
@@ -197281,7 +197391,14 @@ async function buildRunReconstructionReport(sessionId, options = {}) {
197281
197391
  trajectoryReplay,
197282
197392
  trajectoryScore,
197283
197393
  trajectoryInspection,
197284
- agentRuntimeLedger
197394
+ agentRuntimeLedger,
197395
+ durability: buildDurabilitySummary({
197396
+ sessionFile,
197397
+ session,
197398
+ counts,
197399
+ contextManifest,
197400
+ agentRuntimeLedger
197401
+ })
197285
197402
  };
197286
197403
  }
197287
197404
  function renderCoverage(coverage) {
@@ -197325,6 +197442,7 @@ function renderRunReconstruction(report) {
197325
197442
  `Trajectory score: ${report.trajectoryScore.counts.failed} failed, ${report.trajectoryScore.counts.warnings} warnings across ${report.trajectoryScore.counts.rules} rule(s)`,
197326
197443
  `Replay lab: ${report.trajectoryInspection.counts.jumpTargets} event/source jump target(s), redaction=${report.trajectoryInspection.redaction.default}`,
197327
197444
  `AgentRuntime ledger: ${report.agentRuntimeLedger.counts.entries} entries, ${report.agentRuntimeLedger.counts.promotionOperations} dry-run promotion op(s), replay deterministic=${report.agentRuntimeLedger.replay.deterministic ? "yes" : "no"}`,
197445
+ `Durability: reconstructable=${report.durability.reconstructable ? "yes" : "no"}, resume summary=${report.durability.resumeSummaryPresent ? "yes" : "no"}, memory hash=${report.durability.memoryExtractionHashPresent ? "yes" : "no"}, checkpoints=${report.durability.compactionCheckpoints}, pending waits=${report.durability.pendingRequests}`,
197328
197446
  `Coverage: ${renderCoverage(report.coverage)}`,
197329
197447
  `Prompt context: ${report.promptContext.entries} entries (${report.promptContext.projectDocs} docs, ${report.promptContext.mcpServers} MCP servers)`,
197330
197448
  `Context manifest: ${report.contextManifest.entries} entries (${report.contextManifest.projectDocs} docs, ${report.contextManifest.mcpServers} MCP servers, ${report.contextManifest.mcpResources} resources, ${report.contextManifest.mcpPrompts} prompts, ${report.contextManifest.diagnostics} diagnostics)`,
@@ -197828,7 +197946,7 @@ async function streamAttachEvents(context2, handlers, signal) {
197828
197946
  buffer = parsed.remainder;
197829
197947
  for (const event of parsed.events) {
197830
197948
  const payload = JSON.parse(event.data);
197831
- assertHeadlessRuntimeStreamEnvelope2(payload, "remote runner headless stream event");
197949
+ assertHeadlessRuntimeStreamEnvelope3(payload, "remote runner headless stream event");
197832
197950
  switch (payload.type) {
197833
197951
  case "message":
197834
197952
  handlers.onMessage(payload.message);
@@ -199706,7 +199824,7 @@ function summarizeOperatingPlaneInspection(inspection, options = {}) {
199706
199824
  contractVersion: inspection.contract_version,
199707
199825
  generatedAt: inspection.generated_at,
199708
199826
  runCount: inspection.runs.length,
199709
- unavailableSources: uniqueStrings3(inspection.unavailable_sources),
199827
+ unavailableSources: uniqueStrings4(inspection.unavailable_sources),
199710
199828
  runs: runs.map(summarizeOperatingPlaneRun)
199711
199829
  };
199712
199830
  }
@@ -199769,8 +199887,8 @@ function summarizeOperatingPlaneRun(run2) {
199769
199887
  proofPresent,
199770
199888
  proofMissing,
199771
199889
  evidenceRefs: summarizeEvidenceRefs(run2.evidence_refs),
199772
- nextActions: uniqueStrings3(run2.work_items?.map((item) => oneLine(item.next_action))),
199773
- blockers: uniqueStrings3(run2.work_items?.map((item) => oneLine(item.blocker))),
199890
+ nextActions: uniqueStrings4(run2.work_items?.map((item) => oneLine(item.next_action))),
199891
+ blockers: uniqueStrings4(run2.work_items?.map((item) => oneLine(item.blocker))),
199774
199892
  withheld: operatingPlaneWithheldReasons(run2),
199775
199893
  usage: summarizeUsage(run2.usage)
199776
199894
  });
@@ -199787,7 +199905,7 @@ function summarizeProof(run2) {
199787
199905
  { label: "cost", value: proof?.cost_attributed }
199788
199906
  ];
199789
199907
  const proofPresent = fields.filter((field) => field.value === true).map((field) => field.label);
199790
- const proofMissing = uniqueStrings3([
199908
+ const proofMissing = uniqueStrings4([
199791
199909
  ...fields.filter((field) => field.value !== true).map((field) => field.label),
199792
199910
  ...proof?.missing_proof ?? [],
199793
199911
  proof ? void 0 : "value_proof unavailable"
@@ -199825,7 +199943,7 @@ function operatingPlaneIdentitySubject(run2) {
199825
199943
  ]);
199826
199944
  }
199827
199945
  function operatingPlaneWithheldReasons(run2) {
199828
- return uniqueStrings3([
199946
+ return uniqueStrings4([
199829
199947
  ...run2.withholding_reasons ?? [],
199830
199948
  run2.redaction_count && run2.redaction_count > 0 ? `${run2.redaction_count} ${pluralize("redaction", run2.redaction_count)}` : void 0,
199831
199949
  ...run2.unavailable_sources ?? []
@@ -199838,7 +199956,7 @@ function formatEvidenceRef(evidence2) {
199838
199956
  evidence2.uri ? `uri ${evidence2.uri}` : void 0,
199839
199957
  evidence2.revision ? `revision ${evidence2.revision}` : void 0
199840
199958
  ];
199841
- return `${evidence2.id} (${uniqueStrings3(details).join(", ")})`;
199959
+ return `${evidence2.id} (${uniqueStrings4(details).join(", ")})`;
199842
199960
  }
199843
199961
  function formatUsage(usage4) {
199844
199962
  const parts = [
@@ -199848,7 +199966,7 @@ function formatUsage(usage4) {
199848
199966
  typeof usage4.estimatedCostMicros === "number" ? `${usage4.estimatedCostMicros} cost micros` : void 0,
199849
199967
  usage4.currency
199850
199968
  ];
199851
- return uniqueStrings3(parts).join(", ") || void 0;
199969
+ return uniqueStrings4(parts).join(", ") || void 0;
199852
199970
  }
199853
199971
  function firstString5(values) {
199854
199972
  for (const value of values) {
@@ -199868,7 +199986,7 @@ function pushLine(lines, label, value) {
199868
199986
  lines.push(`${label}: ${value}`);
199869
199987
  }
199870
199988
  }
199871
- function uniqueStrings3(values) {
199989
+ function uniqueStrings4(values) {
199872
199990
  const seen = /* @__PURE__ */ new Set();
199873
199991
  const normalized = [];
199874
199992
  for (const value of values ?? []) {