@sema-agent/core 3.0.0 → 5.0.0

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 (153) hide show
  1. package/CHANGELOG.md +2382 -0
  2. package/dist/agents/cascade.d.ts +3 -1
  3. package/dist/agents/cascade.js +31 -32
  4. package/dist/agents/cumulative-stats.d.ts +29 -0
  5. package/dist/agents/cumulative-stats.js +29 -0
  6. package/dist/agents/observer.d.ts +4 -0
  7. package/dist/agents/observer.js +11 -10
  8. package/dist/agents/repair-loop.d.ts +2 -0
  9. package/dist/agents/repair-loop.js +48 -24
  10. package/dist/agents/retain-ledger.d.ts +2 -0
  11. package/dist/agents/retain-ledger.js +6 -5
  12. package/dist/agents/roster-store.d.ts +1 -0
  13. package/dist/agents/roster-store.js +3 -5
  14. package/dist/agents/send-message-tool.d.ts +1 -0
  15. package/dist/agents/send-message-tool.js +2 -0
  16. package/dist/agents/subagent.d.ts +3 -1
  17. package/dist/agents/subagent.js +79 -94
  18. package/dist/agents/teacher.d.ts +1 -9
  19. package/dist/agents/teacher.js +21 -24
  20. package/dist/agents/tool-filter.js +6 -7
  21. package/dist/agents/verify.d.ts +1 -0
  22. package/dist/agents/verify.js +15 -14
  23. package/dist/brain/anthropic.js +24 -21
  24. package/dist/brain/openai.js +24 -21
  25. package/dist/brain/stream-engine.js +5 -2
  26. package/dist/brain/stream-shared.d.ts +1 -0
  27. package/dist/brain/stream-shared.js +14 -0
  28. package/dist/brain/terminal-cause.d.ts +4 -0
  29. package/dist/brain/terminal-cause.js +12 -0
  30. package/dist/brain/tool-call-id.d.ts +1 -0
  31. package/dist/brain/tool-call-id.js +3 -0
  32. package/dist/brain/tool-call-repair.js +2 -1
  33. package/dist/core/arg-summary.d.ts +21 -1
  34. package/dist/core/arg-summary.js +61 -14
  35. package/dist/core/auto-compaction.d.ts +1 -0
  36. package/dist/core/auto-compaction.js +16 -25
  37. package/dist/core/background-agent-store.d.ts +22 -22
  38. package/dist/core/background-agent-store.js +19 -23
  39. package/dist/core/checkpoint-store.d.ts +6 -13
  40. package/dist/core/checkpoint-store.js +11 -5
  41. package/dist/core/file-snapshot-store.d.ts +8 -0
  42. package/dist/core/file-snapshot-store.js +4 -3
  43. package/dist/core/fs-write-gate-policy.js +2 -3
  44. package/dist/core/hooks.d.ts +4 -1
  45. package/dist/core/hooks.js +8 -18
  46. package/dist/core/lsp.js +4 -3
  47. package/dist/core/mailbox-store.d.ts +7 -10
  48. package/dist/core/mcp.d.ts +7 -10
  49. package/dist/core/mcp.js +7 -9
  50. package/dist/core/memory-engine/engine.d.ts +0 -1
  51. package/dist/core/memory-engine/engine.js +24 -34
  52. package/dist/core/memory-engine/file-backend.d.ts +1 -2
  53. package/dist/core/memory-engine/file-backend.js +25 -36
  54. package/dist/core/memory-engine/layout.d.ts +8 -0
  55. package/dist/core/memory-engine/layout.js +60 -4
  56. package/dist/core/memory-engine/scope-contract.js +9 -3
  57. package/dist/core/memory-engine/types.d.ts +1 -1
  58. package/dist/core/permission-rules.js +2 -3
  59. package/dist/core/runner/active-skill-scope.d.ts +0 -1
  60. package/dist/core/runner/active-skill-scope.js +2 -17
  61. package/dist/core/runner/assemble-result.d.ts +2 -7
  62. package/dist/core/runner/assemble-result.js +3 -4
  63. package/dist/core/runner/compaction-call-options.d.ts +7 -0
  64. package/dist/core/runner/compaction-call-options.js +30 -0
  65. package/dist/core/runner/prepare-task.d.ts +6 -23
  66. package/dist/core/runner/prepare-task.js +36 -61
  67. package/dist/core/runner/runtask.d.ts +1 -0
  68. package/dist/core/runner/runtask.js +84 -172
  69. package/dist/core/runner/session-rule-policy.js +7 -5
  70. package/dist/core/runner/teardown-bounded.d.ts +7 -0
  71. package/dist/core/runner/teardown-bounded.js +36 -0
  72. package/dist/core/runner/tool-disclosure.d.ts +2 -5
  73. package/dist/core/runner/turn-attachments.d.ts +5 -15
  74. package/dist/core/runner/turn-attachments.js +1 -1
  75. package/dist/core/safe-notify.d.ts +17 -0
  76. package/dist/core/safe-notify.js +59 -0
  77. package/dist/core/sensitive-path-policy.js +4 -4
  78. package/dist/core/session-reconcile.js +1 -2
  79. package/dist/core/skill-tool-specifier.js +2 -3
  80. package/dist/core/skills-directory.js +2 -3
  81. package/dist/core/store-contracts/checkpoint-store-contract.js +1 -1
  82. package/dist/core/stub-env.d.ts +2 -6
  83. package/dist/core/surrogate-safe-slice.d.ts +4 -0
  84. package/dist/core/surrogate-safe-slice.js +18 -0
  85. package/dist/core/task-registry-monitor.js +8 -13
  86. package/dist/core/task-registry-shared.d.ts +23 -1
  87. package/dist/core/task-registry-shared.js +16 -0
  88. package/dist/core/task-registry.d.ts +6 -1
  89. package/dist/core/task-registry.js +52 -87
  90. package/dist/core/task-tool-shape.d.ts +0 -2
  91. package/dist/core/task-tool-shape.js +2 -5
  92. package/dist/core/tool-errors.js +5 -4
  93. package/dist/core/tool-name-aliases.d.ts +1 -2
  94. package/dist/core/tool-name-aliases.js +42 -59
  95. package/dist/core/tool-policy.js +21 -17
  96. package/dist/core/tool-result-store.d.ts +1 -0
  97. package/dist/core/tool-result-store.js +17 -1
  98. package/dist/core/trace.d.ts +9 -9
  99. package/dist/core/types.d.ts +15 -12
  100. package/dist/core/untrusted-egress.d.ts +4 -2
  101. package/dist/core/untrusted-egress.js +28 -14
  102. package/dist/core/workflow-journal-store.d.ts +9 -20
  103. package/dist/core/workflow-run-store.d.ts +11 -10
  104. package/dist/core/workflow-run-store.js +22 -16
  105. package/dist/engine/compaction/utils.js +4 -2
  106. package/dist/engine/execution-env/node-execution-env.d.ts +2 -24
  107. package/dist/engine/execution-env/node-execution-env.js +1 -1
  108. package/dist/engine/harness/agent-harness.d.ts +1 -0
  109. package/dist/engine/harness/agent-harness.js +13 -33
  110. package/dist/engine/harness/types.d.ts +29 -67
  111. package/dist/engine/llm/types.d.ts +1 -1
  112. package/dist/engine/loop/agent-loop.js +12 -14
  113. package/dist/engine/loop/types.d.ts +11 -9
  114. package/dist/engine/session/memory-repo.d.ts +2 -6
  115. package/dist/engine/session/session.d.ts +5 -30
  116. package/dist/index.d.ts +6 -3
  117. package/dist/index.js +4 -3
  118. package/dist/internal/harness-types.d.ts +3 -1
  119. package/dist/orchestration/run-spec.js +6 -4
  120. package/dist/orchestration/run-workflow-tool.js +3 -36
  121. package/dist/orchestration/workflow-governance.js +2 -1
  122. package/dist/orchestration/workflow.d.ts +4 -11
  123. package/dist/orchestration/workflow.js +164 -204
  124. package/dist/prompt-assembly/packs/sema-default.js +1 -3
  125. package/dist/prompt-assembly/tool-catalog.d.ts +10 -9
  126. package/dist/prompt-assembly/turn-snapshot.d.ts +2 -5
  127. package/dist/prompts/default.js +1 -3
  128. package/dist/prompts/simple-sections.d.ts +0 -1
  129. package/dist/prompts/simple-sections.js +0 -1
  130. package/dist/stores/file/background-agent-store.d.ts +3 -12
  131. package/dist/stores/file/background-agent-store.js +3 -41
  132. package/dist/stores/file/checkpoint-store.js +6 -6
  133. package/dist/stores/file/mailbox-store.d.ts +2 -6
  134. package/dist/stores/file/session-policy-store.js +15 -1
  135. package/dist/stores/file/session-store.d.ts +2 -6
  136. package/dist/stores/file/workflow-journal-store.d.ts +3 -11
  137. package/dist/stores/file/workflow-run-store.d.ts +3 -7
  138. package/dist/stores/file/workflow-run-store.js +4 -17
  139. package/dist/tools/fs/bash-readonly-classifier.d.ts +1 -0
  140. package/dist/tools/fs/bash-readonly-classifier.js +60 -25
  141. package/dist/tools/fs/fs-bash.js +330 -104
  142. package/dist/tools/fs/fs-pdf.d.ts +2 -12
  143. package/dist/tools/fs/fs-shared.js +2 -2
  144. package/dist/tools/fs/fs-write.js +0 -1
  145. package/dist/tools/fs/notebook.d.ts +2 -5
  146. package/dist/tools/fs/safety.d.ts +3 -0
  147. package/dist/tools/fs/safety.js +43 -14
  148. package/dist/tools/fs/search.js +5 -5
  149. package/dist/tools/monitor.d.ts +1 -0
  150. package/dist/tools/monitor.js +7 -5
  151. package/dist/tools/worktree.d.ts +2 -7
  152. package/dist/tools/worktree.js +3 -1
  153. package/package.json +6 -2
@@ -1,5 +1,4 @@
1
1
  import { findToolByName, validateToolArguments } from "../llm/index.js";
2
- import { TOMBSTONED_TOOLS } from "../../core/tool-name-aliases.js";
3
2
  import { resolveAgentCoreStreamFn } from "./runtime-deps.js";
4
3
  function appendTextDeltaToAssistantMessage(message, contentIndex, delta) {
5
4
  const content = [...message.content];
@@ -647,10 +646,16 @@ function partitionToolCalls(toolCalls, tools) {
647
646
  }
648
647
  return batches;
649
648
  }
649
+ function resolveToolConcurrency(configured) {
650
+ if (configured === undefined)
651
+ return 10;
652
+ return Number.isFinite(configured) ? Math.max(1, Math.floor(configured)) : 1;
653
+ }
650
654
  async function runCapped(thunks, limit) {
651
655
  const results = new Array(thunks.length);
652
656
  let next = 0;
653
- const workers = Array.from({ length: Math.max(1, Math.min(limit, thunks.length)) }, async () => {
657
+ const width = Number.isFinite(limit) ? Math.max(1, Math.min(limit, thunks.length)) : 1;
658
+ const workers = Array.from({ length: width }, async () => {
654
659
  while (next < thunks.length) {
655
660
  const i = next++;
656
661
  results[i] = await thunks[i]();
@@ -660,7 +665,7 @@ async function runCapped(thunks, limit) {
660
665
  return results;
661
666
  }
662
667
  async function executeToolCallsPartitioned(currentContext, assistantMessage, toolCalls, config, signal, emit, executor) {
663
- const cap = config.maxToolConcurrency ?? 10;
668
+ const cap = resolveToolConcurrency(config.maxToolConcurrency);
664
669
  const allFinalized = [];
665
670
  const messages = [];
666
671
  let engineCutSeen = false;
@@ -798,7 +803,7 @@ class StreamToolExecutor {
798
803
  this.signal?.aborted ||
799
804
  partialAssistant === null ||
800
805
  !isBatchSafeToolCall(findToolByName(this.context.tools, toolCall.name), toolCall) ||
801
- this.inFlight >= (this.config.maxToolConcurrency ?? 10) ||
806
+ this.inFlight >= resolveToolConcurrency(this.config.maxToolConcurrency) ||
802
807
  this.entries.has(toolCall.id)) {
803
808
  this.barrier = true;
804
809
  return;
@@ -927,18 +932,11 @@ function prepareToolCallArguments(tool, toolCall) {
927
932
  async function prepareToolCall(currentContext, assistantMessage, toolCall, config, signal) {
928
933
  const tool = findToolByName(currentContext.tools, toolCall.name);
929
934
  if (!tool) {
930
- const tombstone = TOMBSTONED_TOOLS[toolCall.name];
931
- if (tombstone !== undefined) {
932
- return {
933
- kind: "immediate",
934
- result: createErrorToolResult(tombstone),
935
- isError: true,
936
- };
937
- }
938
- const available = (currentContext.tools ?? []).map((t) => t.name).join(", ");
935
+ const availableTools = (currentContext.tools ?? []).map((t) => t.name);
936
+ const available = availableTools.join(", ");
939
937
  return {
940
938
  kind: "immediate",
941
- result: createErrorToolResult(`Tool ${toolCall.name} not found.${available ? ` Available tools: ${available}` : ""}`),
939
+ result: createErrorToolResult(`Tool ${toolCall.name} not found.${available ? ` Available tools: ${available}` : ""}`, { details: { code: "tool.not_found", toolName: toolCall.name, availableTools } }),
942
940
  isError: true,
943
941
  };
944
942
  }
@@ -74,21 +74,23 @@ export interface LoopRecoveryOptions {
74
74
  hasLiveWriteoutWindow?: () => boolean;
75
75
  };
76
76
  }
77
+ export interface ToolCutInfo {
78
+ toolCallId: string;
79
+ toolName: string;
80
+ elapsedMs: number;
81
+ settled: Promise<void>;
82
+ }
83
+ export interface LoopToolDeadline {
84
+ deadlineMs: () => number | undefined;
85
+ onCut?: (info: ToolCutInfo) => void;
86
+ }
77
87
  export interface AgentLoopConfig extends SimpleStreamOptions {
78
88
  model: Model;
79
89
  recovery?: LoopRecoveryOptions;
80
90
  maxTokensPerCall?: () => number | undefined;
81
91
  callDeadlineMsPerCall?: () => number | undefined;
82
92
  stallTimeoutsPerCall?: () => import("../llm/types.js").StallTimeouts | undefined;
83
- toolDeadline?: {
84
- deadlineMs: () => number | undefined;
85
- onCut?: (info: {
86
- toolCallId: string;
87
- toolName: string;
88
- elapsedMs: number;
89
- settled: Promise<void>;
90
- }) => void;
91
- };
93
+ toolDeadline?: LoopToolDeadline;
92
94
  maxToolConcurrency?: number;
93
95
  streamingToolExecution?: boolean;
94
96
  convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
@@ -1,4 +1,4 @@
1
- import { type Session, type SessionMetadata, type SessionRepo, type SessionTreeEntry } from "../harness/types.js";
1
+ import { type Session, type SessionForkOptions, type SessionMetadata, type SessionRepo, type SessionTreeEntry } from "../harness/types.js";
2
2
  export declare class InMemorySessionRepo implements SessionRepo<SessionMetadata, {
3
3
  id?: string;
4
4
  }> {
@@ -9,11 +9,7 @@ export declare class InMemorySessionRepo implements SessionRepo<SessionMetadata,
9
9
  open(metadata: SessionMetadata): Promise<Session>;
10
10
  list(): Promise<SessionMetadata[]>;
11
11
  delete(metadata: SessionMetadata): Promise<void>;
12
- fork(sourceMetadata: SessionMetadata, options: {
13
- entryId?: string;
14
- position?: "before" | "at";
15
- id?: string;
16
- }): Promise<Session>;
12
+ fork(sourceMetadata: SessionMetadata, options: SessionForkOptions): Promise<Session>;
17
13
  exportEntries(sessionId: string): Promise<SessionTreeEntry[]>;
18
14
  importEntries(sessionId: string, owner: string | undefined, entries: SessionTreeEntry[]): Promise<void>;
19
15
  }
@@ -1,7 +1,8 @@
1
1
  import type { ImageContent, TextContent } from "../llm/index.js";
2
2
  import type { AgentMessage } from "../loop/types.js";
3
- import type { Session, SessionContext, SessionMetadata, SessionStorage, SessionTreeEntry } from "../harness/types.js";
3
+ import type { Session, SessionContext, SessionMetadata, SessionStorage, SessionTreeEntry, WorkspaceState } from "../harness/types.js";
4
4
  import type { BuildContextOptions } from "../harness/types.js";
5
+ import type { PromptEpochDescriptor } from "../../prompt-assembly/epoch.js";
5
6
  export declare function buildSessionContext(pathEntries: SessionTreeEntry[], opts?: BuildContextOptions): SessionContext;
6
7
  export declare class StoredSession<TMetadata extends SessionMetadata = SessionMetadata> implements Session<TMetadata> {
7
8
  private storage;
@@ -19,40 +20,14 @@ export declare class StoredSession<TMetadata extends SessionMetadata = SessionMe
19
20
  appendMessage(message: AgentMessage): Promise<string>;
20
21
  appendThinkingLevelChange(thinkingLevel: string): Promise<string>;
21
22
  appendModelChange(provider: string, modelId: string): Promise<string>;
22
- appendPromptEpoch(descriptor: {
23
- epoch: number;
24
- artifactDigest: string;
25
- packId: string;
26
- assemblyApi: number;
27
- activatedBy: "session_start" | "compaction" | "legacy_migration";
28
- centerArtifactDigest?: string;
29
- sourceRevision?: string;
30
- }): Promise<string>;
23
+ appendPromptEpoch(descriptor: PromptEpochDescriptor): Promise<string>;
31
24
  appendAnnouncedListing(snapshot: {
32
25
  agents?: readonly string[];
33
26
  skills?: readonly string[];
34
27
  models?: readonly string[];
35
28
  }): Promise<string>;
36
- appendWorkspaceState(state: {
37
- taskRoot: string;
38
- handsCwd?: string;
39
- activeWorktree?: {
40
- worktreeDir: string;
41
- originalCwd: string;
42
- baseSha: string;
43
- entered?: boolean;
44
- };
45
- }): Promise<string>;
46
- getWorkspaceState(): Promise<{
47
- taskRoot: string;
48
- handsCwd?: string;
49
- activeWorktree?: {
50
- worktreeDir: string;
51
- originalCwd: string;
52
- baseSha: string;
53
- entered?: boolean;
54
- };
55
- } | undefined>;
29
+ appendWorkspaceState(state: WorkspaceState): Promise<string>;
30
+ getWorkspaceState(): Promise<WorkspaceState | undefined>;
56
31
  getAnnouncedListing(): Promise<{
57
32
  agents?: string[];
58
33
  skills?: string[];
package/dist/index.d.ts CHANGED
@@ -14,7 +14,7 @@ export { assembleCodeTools, type CodeToolsConfig, CODE_ROLE } from "./scenarios/
14
14
  export { capAggregateToolResults, AGGREGATE_TOOL_RESULT_BUDGET_CHARS, DEFAULT_BUDGET_EXEMPT_TOOLS, type AggregateBudgetOptions, } from "./core/tool-result-budget.js";
15
15
  export { capAggregateMediaBytes, AGGREGATE_MEDIA_BUDGET_BYTES, type MediaStripInfo } from "./core/media-byte-cap.js";
16
16
  export { createAskUserQuestionTool, createDurableQuestionPolicy, QUESTION_AWAITS_RESUME, type OnQuestion, type AskQuestion, type AskQuestionOption, type AskQuestionRequest, type QuestionAnswer, type QuestionAnswerItem, } from "./core/ask-question.js";
17
- export { createLspTool, gitCheckIgnoreFilter, LSP_OPERATIONS, LSP_FAILURE_BRAND, brandLspFailure, lspFailureOf, type LspNoneReason, type LspOperation, type LspServerManager, type LspSession, type LspResult, type LspLocation, type LspSymbolInfo, type LspRequestParams, type LspToolOptions, type LspTransport, type LspReadText, } from "./core/lsp.js";
17
+ export { createLspTool, gitCheckIgnoreFilter, LSP_OPERATIONS, LSP_FAILURE_BRAND, brandLspFailure, lspFailureOf, SharedAbortScope, settleOnAbort, type LspNoneReason, type LspOperation, type LspServerManager, type LspSession, type LspResult, type LspLocation, type LspSymbolInfo, type LspRequestParams, type LspToolOptions, type LspTransport, type LspReadText, } from "./core/lsp.js";
18
18
  export { buildRequest, parseResult, callHierarchyMethod, pathToUri } from "./core/lsp-protocol.js";
19
19
  export { TransportLspSession, type SessionWarmup } from "./core/lsp-session.js";
20
20
  export { LspDiagnosticsRegistry, formatDiagnosticsBlock, formatDiagnosticsSummary, type LspDiagnostic, type LspFileDiagnostics, } from "./core/lsp-diagnostics.js";
@@ -27,6 +27,7 @@ export { BrainError, classifyHttp, type BrainErrorCode } from "./brain/errors.js
27
27
  export { looksDegenerate, inspectDegenerate, trimDegenerateTail } from "./brain/repetition.js";
28
28
  export type { RepetitionEvent, RepetitionInspection } from "./brain/repetition.js";
29
29
  export { computeCostMicroUsd, modelCostToPricing, type ModelPricing, type TokenCounts, } from "./core/pricing.js";
30
+ export { cacheFamilyOf, promptTokensOf, uncachedInputTokensOf, type CacheFamily } from "./core/runner/usage-accounting.js";
30
31
  export { emitTrace, type TraceEvent, type TracerHook } from "./core/trace.js";
31
32
  export { InMemoryStrategyStore, type StrategyStore, type StoredStrategy } from "./core/strategy-store.js";
32
33
  export { createSqlTool, validateReadOnlySql, type SqlToolOptions } from "./tools/sql.js";
@@ -56,6 +57,7 @@ export { getShellConfig, isWslBashLauncher } from "./engine/execution-env/node-e
56
57
  export { isSecretEnvKey, scrubSecretEnv } from "./core/secret-env.js";
57
58
  export { MAX_EXEC_OUTPUT_BYTES, RollingTailBuffer, markTruncated } from "./core/exec-output-tail.js";
58
59
  export type { ExecutionEnv, FileInfo, Result, FileErrorCode, ExecutionErrorCode } from "./internal/harness.js";
60
+ export type { ExecResult } from "./internal/harness.js";
59
61
  export { RemoteExecutionError, hasDestroy, isRemoteExecutionEnv, isSuspendable, isIsolated, missingRestoreSurface, isRetryableRemoteErrorCode, RETRYABLE_REMOTE_ERROR_CODES, } from "./core/remote-env.js";
60
62
  export { withRetry } from "./core/with-retry.js";
61
63
  export type { RetryPolicy, RetryResult } from "./core/with-retry.js";
@@ -80,8 +82,8 @@ export { maybeCompact, type MaybeCompactOptions, type CompactionWindowSafetyInfo
80
82
  export { brainToRuntime } from "./core/runtime.js";
81
83
  export { createSensitivePathPolicy, RECOMMENDED_SENSITIVE_PATTERNS } from "./core/sensitive-path-policy.js";
82
84
  export { createFsWriteGatePolicy, type FsWriteGatePolicyOptions } from "./core/fs-write-gate-policy.js";
83
- export { canonicalToolName, TOMBSTONED_TOOLS } from "./core/tool-name-aliases.js";
84
- export { DEFAULT_SUBAGENT_TOOL_NAME, LEGACY_SUBAGENT_TOOL_NAME, SESSION_BG_DEFAULT_TIMEOUT_SEC } from "./agents/subagent.js";
85
+ export { RETIRED_TOOL_NAMES } from "./core/tool-name-aliases.js";
86
+ export { DEFAULT_SUBAGENT_TOOL_NAME, SESSION_BG_DEFAULT_TIMEOUT_SEC } from "./agents/subagent.js";
85
87
  export { renderTaskNotificationXml, taskNotificationDedupKey, SystemInjectionQueue, type TaskNotificationPayload, type TaskNotificationStatus, type ExternalNotificationInput, type SystemInjection, type SystemInjectionPriority, } from "./core/task-notification.js";
86
88
  export { TaskRegistry, defaultTaskRegistry, createTaskOutputTool, createTaskStopTool, type SemaTaskType, type SemaTaskStatus, type SemaTaskHandle, type ParkedClaimTicket, type TaskAccess, type UnifiedTaskOutput, type TaskRetrievalStatus, type StopSource, type RegisterMonitorInput, type MonitorTimers, MONITOR_BATCH_WINDOW_MS, MONITOR_DEFAULT_TIMEOUT_MS, MONITOR_MAX_TIMEOUT_MS, MONITOR_MAX_BATCHES_PER_MINUTE, canAccessWorkflowRun, DURABLE_AGENT_HANDLE_RE, } from "./core/task-registry.js";
87
89
  export { InMemoryMailboxStore, type MailboxStore, type MailboxMessage, type MailboxLease } from "./core/mailbox-store.js";
@@ -164,6 +166,7 @@ export { type BackgroundAgentStore, type BackgroundAgentRecord, type BackgroundA
164
166
  export { FileBackgroundAgentStore, type FileBackgroundAgentStoreOptions } from "./stores/file/background-agent-store.js";
165
167
  export { type WorkflowJournalStore, type WorkflowJournalEntry, InMemoryWorkflowJournalStore, callKeyOrdinal, JOURNAL_OVERSIZE_ERROR_CODE, } from "./core/workflow-journal-store.js";
166
168
  export { untrustedEgressForHuman, redactHostLeaks, redactSecrets, boundedRedactedSummary } from "./core/untrusted-egress.js";
169
+ export type { RedactionFinding, RedactionReport, RedactionConfidence } from "./core/untrusted-egress.js";
167
170
  export { MemoryRosterStore, FileRosterStore, type RosterStore, type RosterEntry, type RosterAccess, type RosterGcOptions } from "./agents/roster-store.js";
168
171
  export { CONFIG_CATALOG_VERSION, describeConfigCatalog, resolveEffectiveConfig, type ConfigKnob, type ConfigOverrideDeclaration, type ConfigProvenance, type EffectiveConfigField, } from "./config/catalog.js";
169
172
  export { normalizeAgentName } from "./core/task-registry.js";
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ export { assembleCodeTools, CODE_ROLE } from "./scenarios/full-body.js";
12
12
  export { capAggregateToolResults, AGGREGATE_TOOL_RESULT_BUDGET_CHARS, DEFAULT_BUDGET_EXEMPT_TOOLS, } from "./core/tool-result-budget.js";
13
13
  export { capAggregateMediaBytes, AGGREGATE_MEDIA_BUDGET_BYTES } from "./core/media-byte-cap.js";
14
14
  export { createAskUserQuestionTool, createDurableQuestionPolicy, QUESTION_AWAITS_RESUME, } from "./core/ask-question.js";
15
- export { createLspTool, gitCheckIgnoreFilter, LSP_OPERATIONS, LSP_FAILURE_BRAND, brandLspFailure, lspFailureOf, } from "./core/lsp.js";
15
+ export { createLspTool, gitCheckIgnoreFilter, LSP_OPERATIONS, LSP_FAILURE_BRAND, brandLspFailure, lspFailureOf, SharedAbortScope, settleOnAbort, } from "./core/lsp.js";
16
16
  export { buildRequest, parseResult, callHierarchyMethod, pathToUri } from "./core/lsp-protocol.js";
17
17
  export { TransportLspSession } from "./core/lsp-session.js";
18
18
  export { LspDiagnosticsRegistry, formatDiagnosticsBlock, formatDiagnosticsSummary, } from "./core/lsp-diagnostics.js";
@@ -24,6 +24,7 @@ export { selectModel, selectModelOrThrow } from "./core/select-model.js";
24
24
  export { BrainError, classifyHttp } from "./brain/errors.js";
25
25
  export { looksDegenerate, inspectDegenerate, trimDegenerateTail } from "./brain/repetition.js";
26
26
  export { computeCostMicroUsd, modelCostToPricing, } from "./core/pricing.js";
27
+ export { cacheFamilyOf, promptTokensOf, uncachedInputTokensOf } from "./core/runner/usage-accounting.js";
27
28
  export { emitTrace } from "./core/trace.js";
28
29
  export { InMemoryStrategyStore } from "./core/strategy-store.js";
29
30
  export { createSqlTool, validateReadOnlySql } from "./tools/sql.js";
@@ -70,8 +71,8 @@ export { maybeCompact } from "./core/auto-compaction.js";
70
71
  export { brainToRuntime } from "./core/runtime.js";
71
72
  export { createSensitivePathPolicy, RECOMMENDED_SENSITIVE_PATTERNS } from "./core/sensitive-path-policy.js";
72
73
  export { createFsWriteGatePolicy } from "./core/fs-write-gate-policy.js";
73
- export { canonicalToolName, TOMBSTONED_TOOLS } from "./core/tool-name-aliases.js";
74
- export { DEFAULT_SUBAGENT_TOOL_NAME, LEGACY_SUBAGENT_TOOL_NAME, SESSION_BG_DEFAULT_TIMEOUT_SEC } from "./agents/subagent.js";
74
+ export { RETIRED_TOOL_NAMES } from "./core/tool-name-aliases.js";
75
+ export { DEFAULT_SUBAGENT_TOOL_NAME, SESSION_BG_DEFAULT_TIMEOUT_SEC } from "./agents/subagent.js";
75
76
  export { renderTaskNotificationXml, taskNotificationDedupKey, SystemInjectionQueue, } from "./core/task-notification.js";
76
77
  export { TaskRegistry, defaultTaskRegistry, createTaskOutputTool, createTaskStopTool, MONITOR_BATCH_WINDOW_MS, MONITOR_DEFAULT_TIMEOUT_MS, MONITOR_MAX_TIMEOUT_MS, MONITOR_MAX_BATCHES_PER_MINUTE, canAccessWorkflowRun, DURABLE_AGENT_HANDLE_RE, } from "./core/task-registry.js";
77
78
  export { InMemoryMailboxStore } from "./core/mailbox-store.js";
@@ -3,5 +3,7 @@ export type { InvokedSkillRetention } from "../engine/compaction/utils.js";
3
3
  export type { AgentCoreRuntimeDeps } from "../engine/loop/runtime-deps.js";
4
4
  export type { AgentMessage, AgentTool, AgentToolResult, AgentToolUpdateCallback, ThinkingLevel, ToolExecutionMode, } from "../engine/loop/types.js";
5
5
  export type { AgentHarnessEvent, CompactionSettings, ExecutionEnv, ExecutionErrorCode, FileErrorCode, FileInfo, Result, Session, SessionMetadata, SessionRepo, SessionStorage, SessionTreeEntry, Skill, } from "../engine/harness/types.js";
6
- export type { ExecutionEnvExecOptions } from "../engine/harness/types.js";
6
+ export type { ExecutionEnvExecOptions, ExecResult } from "../engine/harness/types.js";
7
7
  export type { SessionWriteOptions, CompactionEntry } from "../engine/harness/types.js";
8
+ export type { ActiveWorktreeSession, WorkspaceState } from "../engine/harness/types.js";
9
+ export type { SessionForkOptions } from "../engine/harness/types.js";
@@ -4,8 +4,9 @@ import { isAbsolute, resolve, sep } from "node:path";
4
4
  import { combinePolicies } from "../core/tool-policy.js";
5
5
  import { delimitUntrusted } from "../core/untrusted-text.js";
6
6
  import { isDurablePause } from "../agents/suspend-guard.js";
7
+ import { isAbsolutePathForm, writeTargetPath } from "../tools/fs/safety.js";
7
8
  import { captureBaseline, resolveFrozenPaths, restoreFrozenPaths, runOracle, snapshotFrozenPaths, specError, } from "../core/spec-contract.js";
8
- const WRITE_TOOLS = new Set(["Write", "Edit", "MultiEdit", "NotebookEdit"]);
9
+ const WRITE_TOOLS = new Set(["Write", "Edit", "NotebookEdit"]);
9
10
  const CASE_INSENSITIVE_FS = process.platform === "darwin" || process.platform === "win32";
10
11
  const pathKey = (p) => {
11
12
  let n = p.replace(/\\/g, "/");
@@ -17,13 +18,14 @@ function frozenDenyPolicy(rootDir, frozenResolved) {
17
18
  const frozen = new Set(frozenResolved.map(pathKey));
18
19
  return {
19
20
  check(req) {
20
- if (!WRITE_TOOLS.has(req.toolName))
21
+ const toolName = req.toolName;
22
+ if (!WRITE_TOOLS.has(toolName))
21
23
  return { action: "allow" };
22
24
  const args = req.args;
23
- const raw = args?.file_path ?? args?.path ?? args?.notebook_path;
25
+ const raw = writeTargetPath(toolName, args);
24
26
  if (typeof raw !== "string" || raw.length === 0)
25
27
  return { action: "allow" };
26
- const absForm = raw.startsWith("/") || /^[A-Za-z]:[\\/]/.test(raw);
28
+ const absForm = isAbsolutePathForm(raw);
27
29
  const abs = pathKey(absForm ? raw : resolve(rootDir, raw));
28
30
  if (frozen.has(abs)) {
29
31
  return { action: "deny", reason: `${raw} is part of the frozen specification surface (read-only).` };
@@ -175,7 +175,6 @@ export async function createRunWorkflowTool(d) {
175
175
  const structuredError = (message) => errorResult(JSON.stringify({ error: message }));
176
176
  return defineTool({
177
177
  name: RUN_WORKFLOW_TOOL_NAME,
178
- aliases: ["RunWorkflow", "run_workflow"],
179
178
  contract: { contractId: "core.workflow@1", implementationRevision: "1" },
180
179
  approvalPreview: (raw) => {
181
180
  const a = (raw ?? {});
@@ -456,7 +455,7 @@ export async function createRunWorkflowTool(d) {
456
455
  },
457
456
  });
458
457
  }
459
- if (d.notifier) {
458
+ {
460
459
  let notified = false;
461
460
  const fire = (notification) => {
462
461
  if (notified)
@@ -467,6 +466,8 @@ export async function createRunWorkflowTool(d) {
467
466
  }
468
467
  catch {
469
468
  }
469
+ if (!d.notifier)
470
+ return;
470
471
  void Promise.resolve()
471
472
  .then(() => d.notifier.notify({
472
473
  runId,
@@ -507,40 +508,6 @@ export async function createRunWorkflowTool(d) {
507
508
  }))
508
509
  .catch(() => { });
509
510
  }
510
- else {
511
- let notified = false;
512
- const fire = (notification) => {
513
- if (notified)
514
- return;
515
- notified = true;
516
- try {
517
- d.taskNotification?.(notification);
518
- }
519
- catch {
520
- }
521
- };
522
- handle.done
523
- .then((res) => fire({
524
- task_id: runId,
525
- task_type: "workflow",
526
- ...(ctx.toolCallId !== undefined ? { toolUseId: ctx.toolCallId } : {}),
527
- status: "completed",
528
- summary: completionSummary(meta.name, res.run),
529
- result: boundedRedactedSummary(res.result, 4000),
530
- usage: workflowUsageBlock(res.run),
531
- diagnostics: workflowDiagnostics(runId, d.journalStore?.locator?.(runId, res.run.scope), res.run.resume?.journalEntries === 0),
532
- completionId: res.run.completionId,
533
- }), (err) => fire({
534
- task_id: runId,
535
- task_type: "workflow",
536
- ...(ctx.toolCallId !== undefined ? { toolUseId: ctx.toolCallId } : {}),
537
- status: "failed",
538
- summary: failureSummary(err, runId),
539
- diagnostics: workflowDiagnostics(runId, undefined),
540
- ...(completionIdFromRejection(err) !== undefined ? { completionId: completionIdFromRejection(err) } : {}),
541
- }))
542
- .catch(() => { });
543
- }
544
511
  return {
545
512
  details: { type: "workflow-run", status: "backgrounded", workflowRunId: runId },
546
513
  content: JSON.stringify({
@@ -1,4 +1,5 @@
1
1
  import { tightenTaskSpec } from "../core/tighten-task-spec.js";
2
+ import { sanitizeUntrustedText } from "../core/untrusted-text.js";
2
3
  import { WorkflowScriptError } from "./workflow-meta.js";
3
4
  export class WorkflowModelNotAllowedError extends Error {
4
5
  modelName;
@@ -81,7 +82,7 @@ function pickWhitelist(scriptSpec) {
81
82
  if (s.systemPrompt !== undefined) {
82
83
  if (typeof s.systemPrompt !== "string")
83
84
  throw new WorkflowScriptError("agent(spec): `systemPrompt` must be a string");
84
- safe.systemPrompt = s.systemPrompt;
85
+ safe.systemPrompt = `[workflow-script-authored persona — task guidance, not engine authority]\n${sanitizeUntrustedText(s.systemPrompt)}`;
85
86
  }
86
87
  if (s.images !== undefined) {
87
88
  if (!Array.isArray(s.images))
@@ -2,7 +2,7 @@ import type { TSchema } from "typebox";
2
2
  import type { Runner } from "../core/runner/runtask.js";
3
3
  import type { AgentDefinition, TaskEvent, TaskResult, TaskSpec } from "../core/types.js";
4
4
  import type { WorkflowRunStore } from "../core/workflow-run-store.js";
5
- import type { WorkflowJournalStore } from "../core/workflow-journal-store.js";
5
+ import type { WorkflowJournalStore, ResumeClaimArgs } from "../core/workflow-journal-store.js";
6
6
  import type { WorkflowRun, WorkflowEvent } from "./workflow-types.js";
7
7
  export * from "./workflow-types.js";
8
8
  export declare const WORKFLOW_SUBAGENT_PROMPT = "You are a subagent spawned by a workflow orchestration script. Use the tools available to complete the task.\n\nCRITICAL: Your final text response is returned **verbatim** as a string to the calling script \u2014 it is your return value, not a message to a human.\n- Output the literal result (data, JSON, text). Do NOT output confirmations like \"Done.\" or \"Sent.\"\n- If asked for JSON, return ONLY the raw JSON \u2014 no code fences, no prose, no markdown.\n- Do NOT address a human user \u2014 there is no user on the other end. Put your answer in your final text response.\n- Do NOT delegate to further sub-agents or start nested workflows; complete the task yourself.\n- Be concise. The script will parse your output.";
@@ -89,6 +89,7 @@ export interface RunWorkflowOptions {
89
89
  maxLogChars?: number;
90
90
  maxResultChars?: number;
91
91
  onEvent?: (e: WorkflowEvent) => void;
92
+ onNotifyError?: (failure: import("../core/safe-notify.js").SafeNotifyFailure) => void;
92
93
  now?: () => number;
93
94
  journalStore?: WorkflowJournalStore;
94
95
  resumeFromRunId?: string;
@@ -131,19 +132,11 @@ export interface WorkflowTimers {
131
132
  clearTimeout(handle: unknown): void;
132
133
  }
133
134
  export declare const workflowResumeClaimFallback: {
134
- acquire(store: WorkflowJournalStore, input: {
135
- sourceRunId: string;
136
- newRunId: string;
137
- scope: string;
138
- }): {
135
+ acquire(store: WorkflowJournalStore, input: ResumeClaimArgs): {
139
136
  granted: boolean;
140
137
  holder?: string;
141
138
  };
142
- release(store: WorkflowJournalStore, input: {
143
- sourceRunId: string;
144
- newRunId: string;
145
- scope: string;
146
- }): void;
139
+ release(store: WorkflowJournalStore, input: ResumeClaimArgs): void;
147
140
  };
148
141
  export declare function startWorkflow<T>(runner: Runner, fn: (ctx: WorkflowRunContext) => Promise<T>, opts?: RunWorkflowOptions, internals?: WorkflowInternals): WorkflowHandle<T>;
149
142
  export declare function runWorkflow<T>(runner: Runner, fn: (ctx: WorkflowRunContext) => Promise<T>, opts?: RunWorkflowOptions, internals?: WorkflowInternals): Promise<RunWorkflowResult<T>>;