@leitwerk-dev/worker 0.3.1 → 0.4.1

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 (82) hide show
  1. package/dist/{chunk-4WPLQCF6.js → chunk-KJCBXN5F.js} +1700 -1244
  2. package/dist/chunk-KJCBXN5F.js.map +1 -0
  3. package/dist/container-entry-main.js +160 -3
  4. package/dist/container-entry-main.js.map +1 -1
  5. package/dist/container-entry.d.ts +1 -0
  6. package/dist/container-entry.d.ts.map +1 -1
  7. package/dist/development-tool-environment.d.ts.map +1 -1
  8. package/dist/diagnostics.d.ts +5 -1
  9. package/dist/diagnostics.d.ts.map +1 -1
  10. package/dist/docker-registry-credentials.d.ts.map +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/ipc.d.ts.map +1 -1
  13. package/dist/logical-prompt-runner.d.ts.map +1 -1
  14. package/dist/missing-tool-recovery-runner.d.ts.map +1 -1
  15. package/dist/pi-adapter.d.ts +2 -0
  16. package/dist/pi-adapter.d.ts.map +1 -1
  17. package/dist/pi-event-reporter.d.ts +2 -0
  18. package/dist/pi-event-reporter.d.ts.map +1 -1
  19. package/dist/pi-inspection.d.ts +5 -0
  20. package/dist/pi-inspection.d.ts.map +1 -0
  21. package/dist/runtime/bootstrap-session.d.ts +4 -1
  22. package/dist/runtime/bootstrap-session.d.ts.map +1 -1
  23. package/dist/runtime/bootstrap.d.ts.map +1 -1
  24. package/dist/runtime/failure-policy.d.ts.map +1 -1
  25. package/dist/runtime/index.d.ts.map +1 -1
  26. package/dist/runtime/llm-turn-execution.d.ts +2 -0
  27. package/dist/runtime/llm-turn-execution.d.ts.map +1 -1
  28. package/dist/runtime/turn-execution.d.ts.map +1 -1
  29. package/dist/session-snapshot-exchange.d.ts.map +1 -1
  30. package/dist/strict-outcome-schema.d.ts +11 -0
  31. package/dist/strict-outcome-schema.d.ts.map +1 -0
  32. package/dist/test-helpers/llm-turn.d.ts +4 -0
  33. package/dist/test-helpers/llm-turn.d.ts.map +1 -0
  34. package/dist/test-helpers/pi-provider.d.ts +13 -0
  35. package/dist/test-helpers/pi-provider.d.ts.map +1 -0
  36. package/dist/transport-error.d.ts +16 -0
  37. package/dist/transport-error.d.ts.map +1 -0
  38. package/dist/turn-outcome-tool-session.d.ts +6 -1
  39. package/dist/turn-outcome-tool-session.d.ts.map +1 -1
  40. package/dist/turn-result-markdown.d.ts +5 -0
  41. package/dist/turn-result-markdown.d.ts.map +1 -1
  42. package/dist/virtual-machine-docker.d.ts +10 -0
  43. package/dist/virtual-machine-docker.d.ts.map +1 -0
  44. package/dist/worker-entry.js +1 -1
  45. package/dist/workspace/checkout-tool.d.ts +6 -0
  46. package/dist/workspace/checkout-tool.d.ts.map +1 -0
  47. package/dist/workspace/manifest.d.ts +2 -0
  48. package/dist/workspace/manifest.d.ts.map +1 -1
  49. package/dist/workspace/node-run-root-git-ops.d.ts +1 -0
  50. package/dist/workspace/node-run-root-git-ops.d.ts.map +1 -1
  51. package/dist/workspace/run-root.d.ts +5 -3
  52. package/dist/workspace/run-root.d.ts.map +1 -1
  53. package/package.json +9 -9
  54. package/src/container-entry.ts +22 -0
  55. package/src/development-tool-environment.ts +2 -0
  56. package/src/diagnostics.ts +6 -1
  57. package/src/docker-registry-credentials.ts +8 -0
  58. package/src/ipc.ts +4 -24
  59. package/src/logical-prompt-runner.ts +45 -41
  60. package/src/missing-tool-recovery-runner.ts +26 -18
  61. package/src/pi-adapter.ts +219 -337
  62. package/src/pi-event-reporter.ts +8 -0
  63. package/src/pi-inspection.ts +126 -0
  64. package/src/runtime/bootstrap-session.ts +12 -1
  65. package/src/runtime/bootstrap.ts +15 -5
  66. package/src/runtime/failure-policy.ts +20 -2
  67. package/src/runtime/index.ts +65 -10
  68. package/src/runtime/llm-turn-execution.ts +28 -1
  69. package/src/runtime/turn-execution.ts +70 -2
  70. package/src/session-snapshot-exchange.ts +2 -0
  71. package/src/strict-outcome-schema.ts +84 -0
  72. package/src/test-helpers/llm-turn.ts +22 -0
  73. package/src/test-helpers/pi-provider.ts +128 -0
  74. package/src/transport-error.ts +92 -0
  75. package/src/turn-outcome-tool-session.ts +123 -26
  76. package/src/turn-result-markdown.ts +23 -6
  77. package/src/virtual-machine-docker.ts +191 -0
  78. package/src/workspace/checkout-tool.ts +68 -0
  79. package/src/workspace/manifest.ts +3 -0
  80. package/src/workspace/node-run-root-git-ops.ts +17 -0
  81. package/src/workspace/run-root.ts +62 -26
  82. package/dist/chunk-4WPLQCF6.js.map +0 -1
package/src/pi-adapter.ts CHANGED
@@ -25,7 +25,12 @@ import type {
25
25
  PiTurnExecutionResult,
26
26
  PiUsageData,
27
27
  } from "@leitwerk-dev/process-sdk";
28
- import { hasErrorCode, isEnoent } from "@leitwerk-dev/process-sdk";
28
+ import {
29
+ compileOutcomeParameters,
30
+ hasErrorCode,
31
+ isEnoent,
32
+ type OutcomeToolParameterSpec,
33
+ } from "@leitwerk-dev/process-sdk";
29
34
  import { resolvePiAgentDir } from "@leitwerk-dev/process-sdk/pi-config";
30
35
  import type { ConfigSnapshot } from "@leitwerk-dev/protocol";
31
36
  import { parseDurationMs } from "@leitwerk-dev/watcher-utils";
@@ -38,8 +43,10 @@ import {
38
43
  type PiBranchOperation,
39
44
  resolveExecutionAnchorEntryId,
40
45
  } from "./pi-branch-guard.js";
46
+ import { installPiInspection } from "./pi-inspection.js";
41
47
  import { createRepositoryBashTool } from "./repository-bash-tool.js";
42
48
  import { buildLeitwerkResourceLoaderOptions } from "./resource-loader-factory.js";
49
+ import { installStrictOutcomeSchemas } from "./strict-outcome-schema.js";
43
50
 
44
51
  const LEITWERK_TOOL_BOOTSTRAP_NAME = "__leitwerk_runtime_bootstrap__";
45
52
 
@@ -188,17 +195,9 @@ export async function inspectPiTreeForPlanning(
188
195
  path.dirname(input.treeFile),
189
196
  input.sessionCwd,
190
197
  );
191
- const entries: Array<Pick<PiTreeEntry, "id" | "parentId">> = [];
192
- const visit = (nodes: readonly PiTreeNode[]) => {
193
- for (const node of nodes) {
194
- entries.push({ id: node.entry.id, parentId: node.entry.parentId });
195
- visit(node.children);
196
- }
197
- };
198
- visit(manager.getTree() as unknown as readonly PiTreeNode[]);
199
198
  return {
200
199
  currentLeafId: manager.getLeafId() ?? null,
201
- entries,
200
+ entries: manager.getEntries().map(({ id, parentId }) => ({ id, parentId })),
202
201
  };
203
202
  }
204
203
 
@@ -233,12 +232,15 @@ interface PiBeforeToolCallContext {
233
232
  toolCall: { name: string };
234
233
  }
235
234
 
235
+ type PiTurnDecision = { action: "end" | "continue" } | undefined;
236
+
236
237
  interface PiAgentLoopConfig {
237
- shouldStopAfterTurn?: (...args: unknown[]) => boolean | Promise<boolean>;
238
+ finishTurn?: (...args: unknown[]) => PiTurnDecision | Promise<PiTurnDecision>;
238
239
  [key: string]: unknown;
239
240
  }
240
241
 
241
242
  interface PiCompletedTurnContext {
243
+ toolResults?: unknown[];
242
244
  message?: {
243
245
  content?: unknown;
244
246
  stopReason?: unknown;
@@ -273,33 +275,10 @@ function toToolSchema(parameters: Record<string, unknown>): Record<string, unkno
273
275
  return parameters;
274
276
  }
275
277
 
276
- const properties: Record<string, unknown> = {};
277
- const required: string[] = [];
278
- for (const [key, spec] of Object.entries(parameters)) {
279
- if (isObjectLike(spec)) {
280
- const {
281
- required: isRequired,
282
- requiredErrorCode: _requiredErrorCode,
283
- invalidErrorCode: _invalidErrorCode,
284
- minItemsErrorCode: _minItemsErrorCode,
285
- minimumErrorCode: _minimumErrorCode,
286
- ...jsonSchemaSpec
287
- } = spec;
288
- properties[key] = { ...jsonSchemaSpec };
289
- if (isRequired === true) {
290
- required.push(key);
291
- }
292
- } else {
293
- properties[key] = { type: "string" };
294
- }
295
- }
296
-
297
- return {
298
- type: "object",
299
- properties,
300
- required,
301
- additionalProperties: false,
302
- };
278
+ return compileOutcomeParameters(parameters as Record<string, OutcomeToolParameterSpec>) as Record<
279
+ string,
280
+ unknown
281
+ >;
303
282
  }
304
283
 
305
284
  const LEITWERK_TOOL_BOOTSTRAP: ToolDefinition = {
@@ -398,18 +377,20 @@ function validateRequestedActiveTools(
398
377
  }
399
378
  }
400
379
 
401
- function toPiRunDetails(input: {
402
- loadedAgentsFiles: Array<{ path: string; content: string }>;
403
- loadedSkills: Array<{ name: string; path: string }>;
404
- availableToolNames: string[];
405
- }): PiRunDetails {
380
+ function toPiRunDetails(
381
+ { resourceLoader }: AgentSessionServices,
382
+ availableToolNames: readonly string[],
383
+ ): PiRunDetails {
406
384
  return {
407
- loadedAgentsFiles: input.loadedAgentsFiles.map((file) => ({
408
- path: file.path,
409
- sizeBytes: Buffer.byteLength(file.content, "utf8"),
385
+ loadedAgentsFiles: resourceLoader.getAgentsFiles().agentsFiles.map(({ path, content }) => ({
386
+ path,
387
+ sizeBytes: Buffer.byteLength(content, "utf8"),
388
+ })),
389
+ loadedSkills: resourceLoader.getSkills().skills.map(({ name, filePath }) => ({
390
+ name,
391
+ path: filePath,
410
392
  })),
411
- loadedSkills: input.loadedSkills.map((skill) => ({ name: skill.name, path: skill.path })),
412
- availableToolNames: [...input.availableToolNames],
393
+ availableToolNames: [...availableToolNames],
413
394
  };
414
395
  }
415
396
 
@@ -589,18 +570,18 @@ class TerminalAcknowledgementRuntime {
589
570
  this.clearTimeout();
590
571
  }
591
572
 
592
- onTurnCompleted(args: readonly unknown[]): boolean | null {
573
+ onTurnCompleted(args: readonly unknown[]): PiTurnDecision {
593
574
  const state = this.control.state();
594
575
  if (!this.acknowledgementTurnStarted) {
595
- if (state !== "outcome_accepted") return null;
576
+ if (state !== "outcome_accepted") return undefined;
596
577
  this.acknowledgementTurnStarted = true;
597
- return false;
578
+ return { action: "continue" };
598
579
  }
599
580
  if (state === "outcome_accepted") {
600
581
  const context = isObjectLike(args[0]) ? (args[0] as PiCompletedTurnContext) : null;
601
582
  this.settleFromMessage(context?.message);
602
583
  }
603
- return true;
584
+ return { action: "end" };
604
585
  }
605
586
 
606
587
  async run(run: () => Promise<void>): Promise<void> {
@@ -882,18 +863,22 @@ function summarizeSessionGlobalDiagnosticDetails(
882
863
  return keys.length > 0 ? { ...base, keys } : base;
883
864
  }
884
865
 
885
- function buildKnownSessionGlobalDiagnostic(
886
- event: AgentSessionEvent,
887
- code: string,
888
- message: string,
889
- ): PiSessionDiagnostic {
890
- return buildSessionDiagnostic({
891
- level: "info",
892
- code,
893
- message,
894
- timestamp: readSessionEventTimestamp(event),
895
- details: summarizeSessionGlobalDiagnosticDetails(event),
896
- });
866
+ const SESSION_GLOBAL_EVENT_MESSAGES = new Map([
867
+ ["session_info_changed", "Pi session info changed"],
868
+ ["agent_start", "Pi agent run started"],
869
+ ["agent_end", "Pi agent run ended"],
870
+ ["agent_settled", "Pi agent run settled"],
871
+ ["queue_update", "Pi session queue updated"],
872
+ ]);
873
+
874
+ const TOOL_CALL_EVENT_TYPES = {
875
+ toolcall_start: "toolcall.start",
876
+ toolcall_delta: "toolcall.delta",
877
+ toolcall_end: "toolcall.end",
878
+ } as const;
879
+
880
+ function singlePiEvent(event: PiEvent): AgentSessionEventTranslation {
881
+ return { piEvents: [event], diagnostics: [] };
897
882
  }
898
883
 
899
884
  function buildUnknownSessionEventDiagnostic(
@@ -956,16 +941,18 @@ export function translateAgentSessionEventEnvelope(
956
941
  turnSequence: number;
957
942
  },
958
943
  ): AgentSessionEventTranslation {
959
- const runtimeEventType = (event as unknown as { type?: unknown }).type;
960
- if (runtimeEventType === "session_info_changed") {
944
+ const globalMessage = SESSION_GLOBAL_EVENT_MESSAGES.get(event.type);
945
+ if (globalMessage) {
961
946
  return {
962
947
  piEvents: [],
963
948
  diagnostics: [
964
- buildKnownSessionGlobalDiagnostic(
965
- event,
966
- "pi.session_info_changed",
967
- "Pi session info changed",
968
- ),
949
+ buildSessionDiagnostic({
950
+ level: "info",
951
+ code: `pi.${event.type}`,
952
+ message: globalMessage,
953
+ timestamp: readSessionEventTimestamp(event),
954
+ details: summarizeSessionGlobalDiagnosticDetails(event),
955
+ }),
969
956
  ],
970
957
  };
971
958
  }
@@ -979,32 +966,22 @@ export function translateAgentSessionEventEnvelope(
979
966
  state.turnSequence = turnIndex;
980
967
  const turnId = `turn-${turnIndex}`;
981
968
  state.currentTurnId = turnId;
982
- return {
983
- piEvents: [
984
- {
985
- type: "turn.start",
986
- turnId,
987
- data: {},
988
- timestamp: toIsoTimestamp((event as { timestamp?: unknown }).timestamp),
989
- },
990
- ],
991
- diagnostics: [],
992
- };
969
+ return singlePiEvent({
970
+ type: "turn.start",
971
+ turnId,
972
+ data: {},
973
+ timestamp: toIsoTimestamp((event as { timestamp?: unknown }).timestamp),
974
+ });
993
975
  }
994
976
  case "turn_end": {
995
977
  const turnId = state.currentTurnId ?? `turn-${state.turnSequence}`;
996
978
  state.currentTurnId = null;
997
- return {
998
- piEvents: [
999
- {
1000
- type: "turn.end",
1001
- turnId,
1002
- data: {},
1003
- timestamp: toIsoTimestamp((event.message as { timestamp?: unknown }).timestamp),
1004
- },
1005
- ],
1006
- diagnostics: [],
1007
- };
979
+ return singlePiEvent({
980
+ type: "turn.end",
981
+ turnId,
982
+ data: {},
983
+ timestamp: toIsoTimestamp((event.message as { timestamp?: unknown }).timestamp),
984
+ });
1008
985
  }
1009
986
  case "message_start":
1010
987
  return { piEvents: [], diagnostics: [] };
@@ -1020,71 +997,25 @@ export function translateAgentSessionEventEnvelope(
1020
997
  const timestamp = toIsoTimestamp((event.message as { timestamp?: unknown }).timestamp);
1021
998
  switch (event.assistantMessageEvent.type) {
1022
999
  case "text_delta":
1023
- return {
1024
- piEvents: [
1025
- {
1026
- type: "stream.delta",
1027
- turnId,
1028
- data: {
1029
- text: event.assistantMessageEvent.delta,
1030
- streamType: "text",
1031
- },
1032
- timestamp,
1033
- },
1034
- ],
1035
- diagnostics: [],
1036
- };
1037
1000
  case "thinking_delta":
1038
- return {
1039
- piEvents: [
1040
- {
1041
- type: "stream.delta",
1042
- turnId,
1043
- data: {
1044
- text: event.assistantMessageEvent.delta,
1045
- streamType: "thinking",
1046
- },
1047
- timestamp,
1048
- },
1049
- ],
1050
- diagnostics: [],
1051
- };
1001
+ return singlePiEvent({
1002
+ type: "stream.delta",
1003
+ turnId,
1004
+ data: {
1005
+ text: event.assistantMessageEvent.delta,
1006
+ streamType: event.assistantMessageEvent.type === "text_delta" ? "text" : "thinking",
1007
+ },
1008
+ timestamp,
1009
+ });
1052
1010
  case "toolcall_start":
1053
- return {
1054
- piEvents: [
1055
- {
1056
- type: "toolcall.start",
1057
- turnId,
1058
- data: normalizePiEventData(assistantMessageEvent),
1059
- timestamp,
1060
- },
1061
- ],
1062
- diagnostics: [],
1063
- };
1064
1011
  case "toolcall_delta":
1065
- return {
1066
- piEvents: [
1067
- {
1068
- type: "toolcall.delta",
1069
- turnId,
1070
- data: normalizePiEventData(assistantMessageEvent),
1071
- timestamp,
1072
- },
1073
- ],
1074
- diagnostics: [],
1075
- };
1076
1012
  case "toolcall_end":
1077
- return {
1078
- piEvents: [
1079
- {
1080
- type: "toolcall.end",
1081
- turnId,
1082
- data: normalizePiEventData(assistantMessageEvent),
1083
- timestamp,
1084
- },
1085
- ],
1086
- diagnostics: [],
1087
- };
1013
+ return singlePiEvent({
1014
+ type: TOOL_CALL_EVENT_TYPES[event.assistantMessageEvent.type],
1015
+ turnId,
1016
+ data: normalizePiEventData(assistantMessageEvent),
1017
+ timestamp,
1018
+ });
1088
1019
  case "start":
1089
1020
  case "done":
1090
1021
  case "error":
@@ -1166,79 +1097,59 @@ export function translateAgentSessionEventEnvelope(
1166
1097
  return { piEvents, diagnostics: [] };
1167
1098
  }
1168
1099
  case "auto_retry_start":
1169
- return {
1170
- piEvents: [
1171
- {
1172
- type: "retry.start",
1173
- turnId: activeTurnId(state),
1174
- data: {
1175
- attempt: event.attempt,
1176
- maxAttempts: event.maxAttempts,
1177
- delayMs: event.delayMs,
1178
- errorMessage: event.errorMessage,
1179
- message: describeRetryStart({
1180
- attempt: event.attempt,
1181
- maxAttempts: event.maxAttempts,
1182
- delayMs: event.delayMs,
1183
- errorMessage: event.errorMessage,
1184
- }),
1185
- },
1186
- timestamp: new Date().toISOString(),
1187
- },
1188
- ],
1189
- diagnostics: [],
1190
- };
1100
+ return singlePiEvent({
1101
+ type: "retry.start",
1102
+ turnId: activeTurnId(state),
1103
+ data: {
1104
+ attempt: event.attempt,
1105
+ maxAttempts: event.maxAttempts,
1106
+ delayMs: event.delayMs,
1107
+ errorMessage: event.errorMessage,
1108
+ message: describeRetryStart({
1109
+ attempt: event.attempt,
1110
+ maxAttempts: event.maxAttempts,
1111
+ delayMs: event.delayMs,
1112
+ errorMessage: event.errorMessage,
1113
+ }),
1114
+ },
1115
+ timestamp: new Date().toISOString(),
1116
+ });
1191
1117
  case "auto_retry_end": {
1192
1118
  const finalError = readNonEmptyString(event.finalError);
1193
- return {
1194
- piEvents: [
1195
- {
1196
- type: "retry.end",
1197
- turnId: activeTurnId(state),
1198
- data: {
1199
- success: event.success,
1200
- attempt: event.attempt,
1201
- ...(finalError ? { finalError } : {}),
1202
- message: describeRetryEnd({
1203
- success: event.success,
1204
- attempt: event.attempt,
1205
- finalError,
1206
- }),
1207
- },
1208
- timestamp: new Date().toISOString(),
1209
- },
1210
- ],
1211
- diagnostics: [],
1212
- };
1119
+ return singlePiEvent({
1120
+ type: "retry.end",
1121
+ turnId: activeTurnId(state),
1122
+ data: {
1123
+ success: event.success,
1124
+ attempt: event.attempt,
1125
+ ...(finalError ? { finalError } : {}),
1126
+ message: describeRetryEnd({
1127
+ success: event.success,
1128
+ attempt: event.attempt,
1129
+ finalError,
1130
+ }),
1131
+ },
1132
+ timestamp: new Date().toISOString(),
1133
+ });
1213
1134
  }
1214
1135
  case "tool_execution_start":
1215
- return {
1216
- piEvents: [
1217
- {
1218
- type: "tool.call",
1219
- turnId: state.currentTurnId ?? `turn-tool-${event.toolCallId}`,
1220
- data: {
1221
- toolCallId: event.toolCallId,
1222
- name: event.toolName,
1223
- arguments: event.args,
1224
- },
1225
- timestamp: new Date().toISOString(),
1226
- },
1227
- ],
1228
- diagnostics: [],
1229
- };
1136
+ return singlePiEvent({
1137
+ type: "tool.call",
1138
+ turnId: state.currentTurnId ?? `turn-tool-${event.toolCallId}`,
1139
+ data: {
1140
+ toolCallId: event.toolCallId,
1141
+ name: event.toolName,
1142
+ arguments: event.args,
1143
+ },
1144
+ timestamp: new Date().toISOString(),
1145
+ });
1230
1146
  case "tool_execution_update":
1231
- return {
1232
- piEvents: [
1233
- {
1234
- type: "tool.update",
1235
- turnId: state.currentTurnId ?? `turn-tool-${event.toolCallId}`,
1236
- data: normalizePiEventData(event as unknown as Record<string, unknown>),
1237
- timestamp: readSessionEventTimestamp(event),
1238
- },
1239
- ],
1240
- diagnostics: [],
1241
- };
1147
+ return singlePiEvent({
1148
+ type: "tool.update",
1149
+ turnId: state.currentTurnId ?? `turn-tool-${event.toolCallId}`,
1150
+ data: normalizePiEventData(event as unknown as Record<string, unknown>),
1151
+ timestamp: readSessionEventTimestamp(event),
1152
+ });
1242
1153
  case "tool_execution_end": {
1243
1154
  const turnId = state.currentTurnId ?? `turn-tool-${event.toolCallId}`;
1244
1155
  const timestamp = new Date().toISOString();
@@ -1254,7 +1165,7 @@ export function translateAgentSessionEventEnvelope(
1254
1165
  timestamp,
1255
1166
  };
1256
1167
  if (!event.isError) {
1257
- return { piEvents: [toolResultEvent], diagnostics: [] };
1168
+ return singlePiEvent(toolResultEvent);
1258
1169
  }
1259
1170
  return {
1260
1171
  piEvents: [
@@ -1277,57 +1188,13 @@ export function translateAgentSessionEventEnvelope(
1277
1188
  };
1278
1189
  }
1279
1190
  case "compaction_start":
1280
- return {
1281
- piEvents: [
1282
- {
1283
- type: "compaction.start",
1284
- turnId: activeTurnId(state),
1285
- data: normalizePiEventData(event as unknown as Record<string, unknown>),
1286
- timestamp: readSessionEventTimestamp(event),
1287
- },
1288
- ],
1289
- diagnostics: [],
1290
- };
1291
1191
  case "compaction_end":
1292
- return {
1293
- piEvents: [
1294
- {
1295
- type: "compaction.end",
1296
- turnId: activeTurnId(state),
1297
- data: normalizePiEventData(event as unknown as Record<string, unknown>),
1298
- timestamp: readSessionEventTimestamp(event),
1299
- },
1300
- ],
1301
- diagnostics: [],
1302
- };
1303
- case "agent_start":
1304
- return {
1305
- piEvents: [],
1306
- diagnostics: [
1307
- buildKnownSessionGlobalDiagnostic(event, "pi.agent_start", "Pi agent run started"),
1308
- ],
1309
- };
1310
- case "agent_end":
1311
- return {
1312
- piEvents: [],
1313
- diagnostics: [
1314
- buildKnownSessionGlobalDiagnostic(event, "pi.agent_end", "Pi agent run ended"),
1315
- ],
1316
- };
1317
- case "agent_settled":
1318
- return {
1319
- piEvents: [],
1320
- diagnostics: [
1321
- buildKnownSessionGlobalDiagnostic(event, "pi.agent_settled", "Pi agent run settled"),
1322
- ],
1323
- };
1324
- case "queue_update":
1325
- return {
1326
- piEvents: [],
1327
- diagnostics: [
1328
- buildKnownSessionGlobalDiagnostic(event, "pi.queue_update", "Pi session queue updated"),
1329
- ],
1330
- };
1192
+ return singlePiEvent({
1193
+ type: event.type === "compaction_start" ? "compaction.start" : "compaction.end",
1194
+ turnId: activeTurnId(state),
1195
+ data: normalizePiEventData(event as unknown as Record<string, unknown>),
1196
+ timestamp: readSessionEventTimestamp(event),
1197
+ });
1331
1198
  default:
1332
1199
  return {
1333
1200
  piEvents: [],
@@ -1352,6 +1219,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1352
1219
  private continuationRetryAbortController: AbortController | null = null;
1353
1220
  private readonly availableToolNames: string[];
1354
1221
  private readonly runDetails: PiRunDetails;
1222
+ private readonly releaseInspection: () => void;
1355
1223
 
1356
1224
  /** @internal */
1357
1225
  constructor(
@@ -1376,6 +1244,17 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1376
1244
  loadedSkills: options.runDetails.loadedSkills.map((skill) => ({ ...skill })),
1377
1245
  availableToolNames: [...options.runDetails.availableToolNames],
1378
1246
  };
1247
+ this.releaseInspection = installPiInspection(
1248
+ session,
1249
+ (capture) =>
1250
+ this.emitSubscribedEvent({
1251
+ type: "inspection",
1252
+ turnId: activeTurnId(this.eventState),
1253
+ timestamp: capture.timestamp,
1254
+ data: { capture },
1255
+ }),
1256
+ () => activeTurnId(this.eventState),
1257
+ );
1379
1258
  }
1380
1259
 
1381
1260
  /** @internal */
@@ -1485,8 +1364,10 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1485
1364
  options.activeTools !== undefined ? [...options.activeTools] : [];
1486
1365
  validateRequestedActiveTools(requestedActiveToolNames, this.availableToolNames);
1487
1366
  const previousActiveToolNames = this.session.getActiveToolNames();
1488
- const needsRuntimeHooks =
1489
- options.shouldBlockToolCall !== undefined || options.terminalAcknowledgement !== undefined;
1367
+ const needsFinishTurnHook = Boolean(
1368
+ options.terminalAcknowledgement || options.shouldStopAfterTurn,
1369
+ );
1370
+ const needsRuntimeHooks = options.shouldBlockToolCall !== undefined || needsFinishTurnHook;
1490
1371
  if (
1491
1372
  customTools.length === 0 &&
1492
1373
  !needsRuntimeHooks &&
@@ -1508,8 +1389,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1508
1389
  const previousCustomTools = [...mutableSession._customTools];
1509
1390
  const previousBeforeToolCall = mutableAgent.beforeToolCall;
1510
1391
  const previousCreateLoopConfig = mutableAgent.createLoopConfig;
1511
- const loopConfigHook = previousCreateLoopConfig;
1512
- if (options.terminalAcknowledgement && typeof loopConfigHook !== "function") {
1392
+ if (needsFinishTurnHook && typeof previousCreateLoopConfig !== "function") {
1513
1393
  throw new Error("Pi SDK version incompatible: agent loop configuration hook unavailable");
1514
1394
  }
1515
1395
  const terminalAcknowledgement = options.terminalAcknowledgement
@@ -1540,28 +1420,31 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1540
1420
  }
1541
1421
  return await previousBeforeToolCall?.(context as never, signal);
1542
1422
  };
1543
- if (terminalAcknowledgement && typeof loopConfigHook === "function") {
1423
+ if (needsFinishTurnHook && typeof previousCreateLoopConfig === "function") {
1544
1424
  mutableAgent.createLoopConfig = (loopOptions?: unknown) => {
1545
- const baseConfig = loopConfigHook.call(mutableAgent, loopOptions);
1546
- const previousShouldStop = baseConfig.shouldStopAfterTurn;
1425
+ const baseConfig = previousCreateLoopConfig.call(mutableAgent, loopOptions);
1426
+ const previousFinishTurn = baseConfig.finishTurn;
1547
1427
  return {
1548
1428
  ...baseConfig,
1549
- shouldStopAfterTurn: async (...args: unknown[]) => {
1550
- const acknowledgementDecision =
1551
- terminalAcknowledgement?.onTurnCompleted(args) ?? null;
1552
- if (acknowledgementDecision !== null) {
1553
- return acknowledgementDecision;
1554
- }
1555
- if (typeof previousShouldStop === "function") {
1556
- return await previousShouldStop(...args);
1557
- }
1558
- return false;
1429
+ finishTurn: async (...args: unknown[]) => {
1430
+ const context = isObjectLike(args[0]) ? (args[0] as PiCompletedTurnContext) : null;
1431
+ if (options.shouldStopAfterTurn?.(context?.toolResults ?? []))
1432
+ return { action: "end" };
1433
+ return (
1434
+ terminalAcknowledgement?.onTurnCompleted(args) ??
1435
+ (await previousFinishTurn?.(...args))
1436
+ );
1559
1437
  },
1560
1438
  };
1561
1439
  };
1562
1440
  }
1563
1441
  }
1564
1442
 
1443
+ const restoreStrictSchemas = installStrictOutcomeSchemas(
1444
+ this.session,
1445
+ customTools,
1446
+ (diagnostic) => this.emitSubscribedDiagnostic(diagnostic),
1447
+ );
1565
1448
  try {
1566
1449
  if (terminalAcknowledgement) {
1567
1450
  await terminalAcknowledgement.run(run);
@@ -1569,6 +1452,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1569
1452
  await run();
1570
1453
  }
1571
1454
  } finally {
1455
+ restoreStrictSchemas();
1572
1456
  terminalAcknowledgement?.dispose();
1573
1457
  mutableSession._customTools = previousCustomTools;
1574
1458
  mutableAgent.beforeToolCall = previousBeforeToolCall;
@@ -1783,6 +1667,8 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1783
1667
  });
1784
1668
  }
1785
1669
  branch.assertResult("continue", entryId, entryId);
1670
+ const timestamp = this.getEntry(entryId)?.timestamp ?? new Date().toISOString();
1671
+ this.emitEntryLink(entryId, timestamp, "user");
1786
1672
  return entryId;
1787
1673
  }
1788
1674
 
@@ -1824,7 +1710,33 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1824
1710
  this.sessionUnsubscribe = this.session.subscribe((event) => this.emitSessionEvent(event));
1825
1711
  }
1826
1712
 
1713
+ private emitEntryLink(entryId: string, timestamp: string, role: string): void {
1714
+ const turnId = activeTurnId(this.eventState);
1715
+ this.emitSubscribedEvent({
1716
+ type: "inspection",
1717
+ turnId,
1718
+ timestamp,
1719
+ data: {
1720
+ capture: {
1721
+ version: 1,
1722
+ id: `entry:${entryId}`,
1723
+ timestamp,
1724
+ fact: { kind: "entry_link", entryId, piTurnId: turnId, role },
1725
+ },
1726
+ },
1727
+ });
1728
+ }
1729
+
1827
1730
  private emitSessionEvent(event: AgentSessionEvent): void {
1731
+ if (event.type === "entry_appended") {
1732
+ const entry = event.entry;
1733
+ this.emitEntryLink(
1734
+ entry.id,
1735
+ entry.timestamp,
1736
+ entry.type === "message" ? entry.message.role : entry.type,
1737
+ );
1738
+ return;
1739
+ }
1828
1740
  const translated = translateAgentSessionEventEnvelope(event, this.eventState);
1829
1741
  for (const piEvent of translated.piEvents) this.emitSubscribedEvent(piEvent);
1830
1742
  for (const diagnostic of translated.diagnostics) this.emitSubscribedDiagnostic(diagnostic);
@@ -1865,6 +1777,7 @@ export class SdkPiTreeHandle implements PiTreeHandle {
1865
1777
 
1866
1778
  /** @internal */
1867
1779
  async close(): Promise<void> {
1780
+ this.releaseInspection();
1868
1781
  if (this.sessionUnsubscribe) {
1869
1782
  this.sessionUnsubscribe();
1870
1783
  this.sessionUnsubscribe = null;
@@ -1940,37 +1853,20 @@ function validateManagedLoadedResources(input: {
1940
1853
  const skills = input.services.resourceLoader.getSkills().skills;
1941
1854
  const prompts = input.services.resourceLoader.getPrompts().prompts;
1942
1855
  const agentsFiles = input.services.resourceLoader.getAgentsFiles().agentsFiles;
1943
- for (const extension of extensions) {
1944
- assertLoadedPathAllowed({
1945
- path: extension.resolvedPath,
1946
- agentDir: input.agentDir,
1947
- workspaceRoot: input.workspaceRoot,
1948
- kind: "extension",
1949
- });
1950
- }
1951
- for (const skill of skills) {
1952
- assertLoadedPathAllowed({
1953
- path: skill.filePath,
1954
- agentDir: input.agentDir,
1955
- workspaceRoot: input.workspaceRoot,
1956
- kind: "skill",
1957
- });
1958
- }
1959
- for (const prompt of prompts) {
1960
- assertLoadedPathAllowed({
1961
- path: prompt.filePath,
1962
- agentDir: input.agentDir,
1963
- workspaceRoot: input.workspaceRoot,
1964
- kind: "prompt",
1965
- });
1966
- }
1967
- for (const agentsFile of agentsFiles) {
1968
- assertLoadedPathAllowed({
1969
- path: agentsFile.path,
1970
- agentDir: input.agentDir,
1971
- workspaceRoot: input.workspaceRoot,
1972
- kind: "context file",
1973
- });
1856
+ for (const [kind, paths] of [
1857
+ ["extension", extensions.map((extension) => extension.resolvedPath)],
1858
+ ["skill", skills.map((skill) => skill.filePath)],
1859
+ ["prompt", prompts.map((prompt) => prompt.filePath)],
1860
+ ["context file", agentsFiles.map((file) => file.path)],
1861
+ ] as const) {
1862
+ for (const loadedPath of paths) {
1863
+ assertLoadedPathAllowed({
1864
+ path: loadedPath,
1865
+ agentDir: input.agentDir,
1866
+ workspaceRoot: input.workspaceRoot,
1867
+ kind,
1868
+ });
1869
+ }
1974
1870
  }
1975
1871
 
1976
1872
  const loadedResourceIds: string[] = [];
@@ -2174,14 +2070,7 @@ export class SdkPiTreeHandleFactory implements PiTreeHandleFactory {
2174
2070
  agentDir: opts.agentDir,
2175
2071
  workspaceRoot: opts.workspaceRoot,
2176
2072
  });
2177
- const runDetails = toPiRunDetails({
2178
- loadedAgentsFiles: services.resourceLoader.getAgentsFiles().agentsFiles,
2179
- loadedSkills: services.resourceLoader.getSkills().skills.map((skill) => ({
2180
- name: skill.name,
2181
- path: skill.filePath,
2182
- })),
2183
- availableToolNames: opts.piConfig?.availableToolNames ?? [],
2184
- });
2073
+ const runDetails = toPiRunDetails(services, opts.piConfig?.availableToolNames ?? []);
2185
2074
  this.preparedServices.set(managedServicesKey(opts.agentDir, opts.sessionCwd), services);
2186
2075
  return {
2187
2076
  loadedResourceIds,
@@ -2251,14 +2140,7 @@ export class SdkPiTreeHandleFactory implements PiTreeHandleFactory {
2251
2140
  noTools: "builtin",
2252
2141
  });
2253
2142
  getMutableSession(session)._refreshToolRegistry({ activeToolNames: [] });
2254
- const runDetails = toPiRunDetails({
2255
- loadedAgentsFiles: services.resourceLoader.getAgentsFiles().agentsFiles,
2256
- loadedSkills: services.resourceLoader.getSkills().skills.map((skill) => ({
2257
- name: skill.name,
2258
- path: skill.filePath,
2259
- })),
2260
- availableToolNames,
2261
- });
2143
+ const runDetails = toPiRunDetails(services, availableToolNames);
2262
2144
  return new SdkPiTreeHandle(session, {
2263
2145
  treeFile: opts.treeFile,
2264
2146
  isResumed: opts.resume,