@themoltnet/pi-extension 0.31.1 → 0.32.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.
package/dist/index.d.ts CHANGED
@@ -382,6 +382,22 @@ export declare interface ExecutePiTaskOptions {
382
382
  * the attempt fails with output_validation_failed.
383
383
  */
384
384
  maxSubmitValidationRetries?: number;
385
+ /**
386
+ * Number of same-session re-prompts when the model ends its turn WITHOUT
387
+ * calling the submit-output tool at all (no captured payload and no
388
+ * exhausted validation budget). Distinct from
389
+ * `maxSubmitValidationRetries`, which recovers *invalid-args* submit calls.
390
+ * Each re-prompt names the submit tool and forbids a prose reply. When the
391
+ * budget is spent the attempt still fails with `submit_output_missing`.
392
+ * Only applies to task types that register a submit tool. Default `3`. Set
393
+ * to `0` to disable. See #1528.
394
+ */
395
+ maxSubmitMissingReprompts?: number;
396
+ /**
397
+ * Continuation prompt sent when a turn ends without a submit call. Defaults
398
+ * to `buildSubmitMissingPrompt(<tool name>)`.
399
+ */
400
+ submitMissingPrompt?: string;
385
401
  /**
386
402
  * Cap provider-error retries inside the same Pi session. A retry is attempted
387
403
  * only after a Pi assistant turn ends with `stopReason: "error"` and the
package/dist/index.js CHANGED
@@ -14226,6 +14226,86 @@ var PRODUCER_TASK_TYPES = new Set([
14226
14226
  "render_pack",
14227
14227
  "run_eval"
14228
14228
  ]);
14229
+ function isNonEmptyString(value) {
14230
+ return typeof value === "string" && value.length > 0;
14231
+ }
14232
+ function criterionWeight(criterion, index) {
14233
+ if (typeof criterion.weight === "number") return criterion.weight;
14234
+ if (typeof criterion.max_score === "number") return criterion.max_score / 100;
14235
+ if (typeof criterion.maxScore === "number") return criterion.maxScore / 100;
14236
+ throw new TaskBuildError([{
14237
+ field: `successCriteria/rubric/criteria/${index}/weight`,
14238
+ message: "criterion is missing weight or max_score"
14239
+ }]);
14240
+ }
14241
+ /**
14242
+ * Normalize authoring-time rubric criteria to canonical MoltNet rubric
14243
+ * criteria. Accepts `{id,title,description,weight}` and
14244
+ * `{name,description,max_score}` style inputs, strips authoring-only fields,
14245
+ * and fills a default scoring mode.
14246
+ */
14247
+ function normalizeRubricCriteria(criteria, options) {
14248
+ const errors = [];
14249
+ const normalized = criteria.map((criterion, index) => {
14250
+ const id = criterion.id ?? criterion.name;
14251
+ const description = criterion.description ?? criterion.title;
14252
+ if (!isNonEmptyString(id)) errors.push({
14253
+ field: `successCriteria/rubric/criteria/${index}/id`,
14254
+ message: "criterion is missing id or name"
14255
+ });
14256
+ if (!isNonEmptyString(description)) errors.push({
14257
+ field: `successCriteria/rubric/criteria/${index}/description`,
14258
+ message: "criterion is missing description or title"
14259
+ });
14260
+ return {
14261
+ id: id ?? "",
14262
+ description: description ?? "",
14263
+ weight: criterionWeight(criterion, index),
14264
+ scoring: criterion.scoring ?? options?.scoring ?? "llm_score"
14265
+ };
14266
+ });
14267
+ if (errors.length > 0) throw new TaskBuildError(errors);
14268
+ return normalized;
14269
+ }
14270
+ /**
14271
+ * Build a canonical `SuccessCriteria` envelope from rubric/checklist-style
14272
+ * criteria. This keeps rubrics readable at the authoring boundary while
14273
+ * preserving the strict task schema on the wire.
14274
+ */
14275
+ function buildRubricSuccessCriteria(options) {
14276
+ const rubric = {
14277
+ rubricId: options.rubricId,
14278
+ version: options.version ?? "v1",
14279
+ criteria: normalizeRubricCriteria(options.criteria, { scoring: options.scoring }),
14280
+ ...options.contentHash ? { contentHash: options.contentHash } : {},
14281
+ ...options.preamble ? { preamble: options.preamble } : {},
14282
+ ...options.scope ? { scope: options.scope } : {}
14283
+ };
14284
+ const weightError = validateRubricWeights(rubric);
14285
+ if (weightError) throw new TaskBuildError([{
14286
+ field: "successCriteria/rubric/criteria",
14287
+ message: weightError
14288
+ }]);
14289
+ return {
14290
+ version: 1,
14291
+ rubric
14292
+ };
14293
+ }
14294
+ function resolveJudgeEvalAttemptTarget(target) {
14295
+ if ("judgeEvalTarget" in target && typeof target.judgeEvalTarget === "function") return target.judgeEvalTarget();
14296
+ if ("targetTaskId" in target) return {
14297
+ targetTaskId: target.targetTaskId,
14298
+ targetAttemptN: target.targetAttemptN
14299
+ };
14300
+ if ("taskId" in target) return {
14301
+ targetTaskId: target.taskId,
14302
+ targetAttemptN: target.accepted?.attemptN ?? target.attemptN ?? 1
14303
+ };
14304
+ throw new TaskBuildError([{
14305
+ field: "target",
14306
+ message: "judge_eval_attempt target is missing task id"
14307
+ }]);
14308
+ }
14229
14309
  /**
14230
14310
  * Fluent, network-free builder for a `tasks.create` body. Encodes the
14231
14311
  * non-obvious task schema (context arrays, success-criteria gates,
@@ -14676,6 +14756,20 @@ function buildJudgeEvalAttempt(input) {
14676
14756
  return buildTask("judge_eval_attempt", input);
14677
14757
  }
14678
14758
  /**
14759
+ * Build a `judge_eval_attempt` task from an accepted `run_eval` result (or a
14760
+ * small target tuple) plus human-friendly rubric criteria.
14761
+ *
14762
+ * @param target - A `TaskResultReader` or `{targetTaskId,targetAttemptN}` tuple.
14763
+ * @param options - Rubric metadata and eval/checklist-style criteria.
14764
+ * @returns A typed {@link TaskBuilder}.
14765
+ */
14766
+ function buildJudgeEvalAttemptForRunEval(target, options) {
14767
+ return buildJudgeEvalAttempt({
14768
+ ...resolveJudgeEvalAttemptTarget(target),
14769
+ successCriteria: buildRubricSuccessCriteria(options)
14770
+ });
14771
+ }
14772
+ /**
14679
14773
  * Build a `pr_review` task. Requires `subject` + `successCriteria`. Note the
14680
14774
  * rubric criteria must use `boolean` scoring for this task type.
14681
14775
  *
@@ -14713,7 +14807,9 @@ var TaskResultReader = class {
14713
14807
  accepted;
14714
14808
  /** Token / cost usage for the accepted attempt, if reported. */
14715
14809
  usage;
14810
+ /** Task id for the task whose accepted attempt is being read. */
14716
14811
  taskId;
14812
+ /** CID of the accepted attempt output. */
14717
14813
  outputCid;
14718
14814
  constructor(task, attempt) {
14719
14815
  const errors = [];
@@ -14806,6 +14902,19 @@ var TaskResultReader = class {
14806
14902
  };
14807
14903
  }
14808
14904
  /**
14905
+ * Return the target tuple required by `judge_eval_attempt`.
14906
+ *
14907
+ * This intentionally uses the accepted attempt number, not merely the
14908
+ * attempt object passed to the reader, so a downstream judge is pinned to
14909
+ * the producer output that the task accepted.
14910
+ */
14911
+ judgeEvalTarget() {
14912
+ return {
14913
+ targetTaskId: this.taskId,
14914
+ targetAttemptN: this.accepted.attemptN
14915
+ };
14916
+ }
14917
+ /**
14809
14918
  * Build a `TaskRef` that anchors a downstream task to this accepted output
14810
14919
  * and points at one persistent task artifact by CID.
14811
14920
  *
@@ -14943,6 +15052,7 @@ function createTasksNamespace(context) {
14943
15052
  buildAssessBrief,
14944
15053
  buildJudgePack,
14945
15054
  buildJudgeEvalAttempt,
15055
+ buildJudgeEvalAttemptForRunEval,
14946
15056
  buildPrReview,
14947
15057
  async readResult(taskOrId) {
14948
15058
  const task = typeof taskOrId === "string" ? unwrapResult(await getTask({
@@ -25621,6 +25731,7 @@ function createSubmitOutputTool(taskType, opts = {}) {
25621
25731
  };
25622
25732
  }
25623
25733
  }),
25734
+ toolName: contract.toolName,
25624
25735
  getCaptured: () => captured,
25625
25736
  getCallCount: () => callCount,
25626
25737
  getInvalidCallCount: () => invalidCallCount,
@@ -26316,7 +26427,8 @@ async function executePiTask(claimedTask, reporter, opts) {
26316
26427
  const message = err instanceof Error ? err.message : String(err);
26317
26428
  reporterError = {
26318
26429
  code: "reporter_failed",
26319
- message
26430
+ message,
26431
+ retryable: true
26320
26432
  };
26321
26433
  process.stderr.write(`[reporter] ${message}\n`);
26322
26434
  }
@@ -26383,9 +26495,9 @@ async function executePiTask(claimedTask, reporter, opts) {
26383
26495
  }
26384
26496
  });
26385
26497
  let runError = null;
26386
- runError = (await promptWithProviderErrorRetries({
26387
- session,
26388
- initialPrompt: taskPrompt,
26498
+ const runPrompt = (promptText) => promptWithProviderErrorRetries({
26499
+ session: liveSession,
26500
+ initialPrompt: promptText,
26389
26501
  cancelSignal: reporter.cancelSignal,
26390
26502
  isCapAborted: () => capAbort !== null,
26391
26503
  getProviderErrorState: () => ({
@@ -26404,7 +26516,33 @@ async function executePiTask(claimedTask, reporter, opts) {
26404
26516
  message,
26405
26517
  phase: "session_prompt"
26406
26518
  })
26407
- })).runError;
26519
+ });
26520
+ const submitMissingConfig = resolveSubmitMissingConfig({
26521
+ submitToolHandle,
26522
+ maxSubmitMissingReprompts: opts.maxSubmitMissingReprompts,
26523
+ submitMissingPrompt: opts.submitMissingPrompt
26524
+ });
26525
+ const promptResult = await promptUntilSubmitted({
26526
+ runPrompt,
26527
+ initialPrompt: taskPrompt,
26528
+ submitMissingPrompt: submitMissingConfig.submitMissingPrompt,
26529
+ maxSubmitMissingReprompts: submitMissingConfig.maxSubmitMissingReprompts,
26530
+ getSubmitState: submitMissingConfig.getSubmitState,
26531
+ isStopped: () => submitRepromptStopped({
26532
+ cancelled: reporter.cancelSignal.aborted,
26533
+ capAborted: capAbort !== null,
26534
+ llmAbort
26535
+ }),
26536
+ onSubmitReprompt: async (event) => {
26537
+ await emit("info", event);
26538
+ }
26539
+ });
26540
+ runError = promptResult.runError;
26541
+ if (promptResult.submitReprompts > 0) await emit("info", {
26542
+ event: "submit_missing_summary",
26543
+ submitReprompts: promptResult.submitReprompts,
26544
+ captured: submitToolHandle ? submitToolHandle.getCaptured() !== null : false
26545
+ });
26408
26546
  if (subagentHandle && subagentHandle.getCallCount() > 0) await emit("info", {
26409
26547
  event: "subagent_summary",
26410
26548
  callCount: subagentHandle.getCallCount()
@@ -26443,10 +26581,16 @@ async function executePiTask(claimedTask, reporter, opts) {
26443
26581
  });
26444
26582
  }
26445
26583
  else if (submitToolHandle) {
26446
- parseError = submitToolHandle.getExhaustedValidationFailure() ?? {
26584
+ const exhausted = submitToolHandle.getExhaustedValidationFailure();
26585
+ parseError = exhausted ?? {
26447
26586
  code: "submit_output_missing",
26448
26587
  message: "Agent did not satisfy the promised submit-output criterion: no valid task submit tool call was captured before the session ended."
26449
26588
  };
26589
+ if (!exhausted) recordTaskOutputParseResult({
26590
+ taskType: task.taskType,
26591
+ model: opts.model,
26592
+ code: "output_missing"
26593
+ });
26450
26594
  await emit("error", {
26451
26595
  message: parseError.message,
26452
26596
  phase: "output_validation"
@@ -26494,9 +26638,11 @@ async function executePiTask(claimedTask, reporter, opts) {
26494
26638
  retryable: false
26495
26639
  }
26496
26640
  };
26497
- const status = runError || llmAbort || parseError || reporterError ? "failed" : "completed";
26498
- const errorCode = runError?.code ?? parseError?.code ?? reporterError?.code ?? (llmAbort ? "llm_api_error" : void 0);
26499
- const errorMessage = runError?.message ?? parseError?.message ?? reporterError?.message ?? (llmAbort ? llmErrorMessage ?? "LLM API error during turn" : void 0);
26641
+ const reporterErrorSnapshot = reporterError;
26642
+ const status = runError || llmAbort || parseError || reporterErrorSnapshot ? "failed" : "completed";
26643
+ const errorCode = runError?.code ?? parseError?.code ?? reporterErrorSnapshot?.code ?? (llmAbort ? "llm_api_error" : void 0);
26644
+ const errorMessage = runError?.message ?? parseError?.message ?? reporterErrorSnapshot?.message ?? (llmAbort ? llmErrorMessage ?? "LLM API error during turn" : void 0);
26645
+ const errorRetryable = reporterErrorSnapshot && errorCode === reporterErrorSnapshot.code && errorMessage === reporterErrorSnapshot.message ? reporterErrorSnapshot.retryable ?? false : false;
26500
26646
  return {
26501
26647
  taskId: task.id,
26502
26648
  attemptN,
@@ -26508,7 +26654,7 @@ async function executePiTask(claimedTask, reporter, opts) {
26508
26654
  ...errorCode && errorMessage ? { error: {
26509
26655
  code: errorCode,
26510
26656
  message: errorMessage,
26511
- retryable: false
26657
+ retryable: errorRetryable
26512
26658
  } } : {}
26513
26659
  };
26514
26660
  } catch (err) {
@@ -26723,6 +26869,102 @@ async function promptWithProviderErrorRetries(args) {
26723
26869
  promptText = args.retryPrompt;
26724
26870
  }
26725
26871
  }
26872
+ /**
26873
+ * Continuation prompt used to recover a session that ended without calling
26874
+ * the submit-output tool. Names the exact tool and forbids a prose reply so a
26875
+ * model that "answered" in text is pushed to actually emit the tool call.
26876
+ */
26877
+ function buildSubmitMissingPrompt(toolName) {
26878
+ return `You ended your turn but did not call the required \`${toolName}\` tool, so no output was captured and the task is not yet complete. Call \`${toolName}\` now with the final structured output exactly as described in the task prompt. Do not reply with prose, a summary, or an apology — the only way to finish is to call the tool.`;
26879
+ }
26880
+ /**
26881
+ * Whether the submit-missing re-prompt loop must stop before the next nudge.
26882
+ *
26883
+ * `llmAbort` matters as much as cancel/cap: when a turn ended with
26884
+ * `stopReason: 'error'` and the provider-error retry budget is spent (or the
26885
+ * error is non-retryable), `promptWithProviderErrorRetries` returns
26886
+ * `runError: null` yet leaves `llmAbort` set. Re-prompting then would nudge a
26887
+ * dead provider N more times (extra prompts + backoff) and emit misleading
26888
+ * `submit_missing_reprompt` events. We only re-prompt after a genuinely clean
26889
+ * `end_turn`.
26890
+ */
26891
+ function submitRepromptStopped(state) {
26892
+ return state.cancelled || state.capAborted || state.llmAbort;
26893
+ }
26894
+ /**
26895
+ * Resolve the submit-missing recovery config from the registered submit tool
26896
+ * (if any) plus caller overrides. Extracted as a pure function so the
26897
+ * default-budget / disable-when-no-tool / gate-mapping logic is unit-tested —
26898
+ * `executePiTask` itself needs a booted VM and can't cover this seam.
26899
+ *
26900
+ * The default budget (3) is deliberately one higher than the invalid-args
26901
+ * correction budget (`maxSubmitValidationRetries`, default 2): a model that
26902
+ * never called the tool just needs a clear nudge, which converts more cheaply
26903
+ * and more often than fixing a malformed payload, so the extra attempt is
26904
+ * worth it.
26905
+ */
26906
+ function resolveSubmitMissingConfig(args) {
26907
+ const handle = args.submitToolHandle;
26908
+ if (!handle) return {
26909
+ maxSubmitMissingReprompts: 0,
26910
+ submitMissingPrompt: "",
26911
+ getSubmitState: () => null
26912
+ };
26913
+ return {
26914
+ maxSubmitMissingReprompts: args.maxSubmitMissingReprompts ?? 3,
26915
+ submitMissingPrompt: args.submitMissingPrompt ?? buildSubmitMissingPrompt(handle.toolName),
26916
+ getSubmitState: () => ({
26917
+ captured: handle.getCaptured() !== null,
26918
+ exhausted: handle.getExhaustedValidationFailure() !== null
26919
+ })
26920
+ };
26921
+ }
26922
+ /**
26923
+ * Drive a Pi session until it either captures a valid submit-output call or
26924
+ * exhausts the submit-missing re-prompt budget.
26925
+ *
26926
+ * This is the third same-session recovery path, complementing the two that
26927
+ * already existed:
26928
+ * 1. Invalid submit args → the submit tool returns `isError`, the model
26929
+ * re-calls within the same turn (see `submit-output-tool.ts`).
26930
+ * 2. Provider/LLM API errors → `promptWithProviderErrorRetries` re-prompts.
26931
+ *
26932
+ * The gap this closes: a model (typically a weaker one) that ends its turn
26933
+ * cleanly with a prose answer and *never calls the submit tool at all*. With
26934
+ * neither a captured payload nor an exhausted validation budget, the executor
26935
+ * would otherwise fail straight to `submit_output_missing` with no chance to
26936
+ * recover. Here we nudge the model — up to `maxSubmitMissingReprompts` times —
26937
+ * to call the submit tool. Pi cannot force `toolChoice`, so this re-prompt is
26938
+ * the only in-session lever short of patching Pi. See issue #1528.
26939
+ */
26940
+ async function promptUntilSubmitted(args) {
26941
+ const first = await args.runPrompt(args.initialPrompt);
26942
+ if (first.runError) return {
26943
+ runError: first.runError,
26944
+ submitReprompts: 0
26945
+ };
26946
+ let submitReprompts = 0;
26947
+ while (submitReprompts < args.maxSubmitMissingReprompts) {
26948
+ if (args.isStopped()) break;
26949
+ const state = args.getSubmitState();
26950
+ if (!state || state.captured || state.exhausted) break;
26951
+ submitReprompts += 1;
26952
+ await args.onSubmitReprompt?.({
26953
+ event: "submit_missing_reprompt",
26954
+ retry: submitReprompts,
26955
+ maxReprompts: args.maxSubmitMissingReprompts
26956
+ });
26957
+ const pass = await args.runPrompt(args.submitMissingPrompt);
26958
+ if (pass.runError) return {
26959
+ runError: pass.runError,
26960
+ submitReprompts
26961
+ };
26962
+ }
26963
+ return {
26964
+ runError: null,
26965
+ submitReprompts
26966
+ };
26967
+ }
26726
26968
  function sanitizeProviderErrorRetryReason(value) {
26727
26969
  return redactRetryTriageSecrets(value ?? "Pi turn ended with stopReason=error").slice(0, 500);
26728
26970
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@themoltnet/pi-extension",
3
- "version": "0.31.1",
3
+ "version": "0.32.0",
4
4
  "type": "module",
5
5
  "description": "MoltNet pi extension — sandboxed tool execution in Gondolin VMs with MoltNet identity and persistent memory",
6
6
  "keywords": [
@@ -36,8 +36,8 @@
36
36
  "@earendil-works/gondolin": "^0.9.1",
37
37
  "@opentelemetry/api": "^1.9.0",
38
38
  "typebox": "^1.2.8",
39
- "@themoltnet/agent-runtime": "0.33.2",
40
- "@themoltnet/sdk": "0.117.0"
39
+ "@themoltnet/agent-runtime": "0.34.0",
40
+ "@themoltnet/sdk": "0.118.0"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "@earendil-works/pi-coding-agent": ">=0.74.0",