@promptbook/cli 0.112.0-121 β†’ 0.112.0-123

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 (34) hide show
  1. package/apps/agents-server/src/app/agents/[agentName]/api/user-chats/[chatId]/messages/route.ts +4 -11
  2. package/esm/index.es.js +1353 -277
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/scripts/run-codex-prompts/common/resolveAgentSystemMessage.d.ts +6 -0
  5. package/esm/scripts/run-codex-prompts/main/findUnwrittenPrompts.d.ts +19 -0
  6. package/esm/scripts/run-codex-prompts/main/runCodexPromptsServer.d.ts +27 -0
  7. package/esm/scripts/run-codex-prompts/main/runPromptRound.d.ts +2 -1
  8. package/esm/scripts/run-codex-prompts/server/coderServerHtml.d.ts +9 -0
  9. package/esm/scripts/run-codex-prompts/server/runCoderHttpServer.d.ts +23 -0
  10. package/esm/scripts/run-codex-prompts/server/updatePromptSection.d.ts +9 -0
  11. package/esm/src/cli/cli-commands/coder/find-unwritten.d.ts +10 -0
  12. package/esm/src/cli/cli-commands/coder/server.d.ts +13 -0
  13. package/esm/src/version.d.ts +1 -1
  14. package/package.json +1 -1
  15. package/src/cli/cli-commands/coder/find-unwritten.ts +58 -0
  16. package/src/cli/cli-commands/coder/init.ts +4 -1
  17. package/src/cli/cli-commands/coder/run.ts +26 -11
  18. package/src/cli/cli-commands/coder/server.ts +239 -0
  19. package/src/cli/cli-commands/coder.ts +6 -0
  20. package/src/other/templates/getTemplatesPipelineCollection.ts +825 -1034
  21. package/src/version.ts +2 -2
  22. package/src/versions.txt +2 -1
  23. package/umd/index.umd.js +1355 -279
  24. package/umd/index.umd.js.map +1 -1
  25. package/umd/scripts/run-codex-prompts/common/resolveAgentSystemMessage.d.ts +6 -0
  26. package/umd/scripts/run-codex-prompts/main/findUnwrittenPrompts.d.ts +19 -0
  27. package/umd/scripts/run-codex-prompts/main/runCodexPromptsServer.d.ts +27 -0
  28. package/umd/scripts/run-codex-prompts/main/runPromptRound.d.ts +2 -1
  29. package/umd/scripts/run-codex-prompts/server/coderServerHtml.d.ts +9 -0
  30. package/umd/scripts/run-codex-prompts/server/runCoderHttpServer.d.ts +23 -0
  31. package/umd/scripts/run-codex-prompts/server/updatePromptSection.d.ts +9 -0
  32. package/umd/src/cli/cli-commands/coder/find-unwritten.d.ts +10 -0
  33. package/umd/src/cli/cli-commands/coder/server.d.ts +13 -0
  34. package/umd/src/version.d.ts +1 -1
package/esm/index.es.js CHANGED
@@ -20,7 +20,7 @@ import { JSDOM } from 'jsdom';
20
20
  import CryptoJS from 'crypto-js';
21
21
  import showdown from 'showdown';
22
22
  import glob from 'glob-promise';
23
- import http from 'http';
23
+ import http, { createServer } from 'http';
24
24
  import express from 'express';
25
25
  import { Server } from 'socket.io';
26
26
  import * as OpenApiValidator from 'express-openapi-validator';
@@ -31,14 +31,14 @@ import Anthropic from '@anthropic-ai/sdk';
31
31
  import Bottleneck from 'bottleneck';
32
32
  import { OpenAIClient, AzureKeyCredential } from '@azure/openai';
33
33
  import { Subject, BehaviorSubject } from 'rxjs';
34
- import { lookup, extension } from 'mime-types';
35
- import papaparse from 'papaparse';
36
34
  import { fileSearchTool, tool, Agent as Agent$1, webSearchTool, run, setDefaultOpenAIClient, setDefaultOpenAIKey } from '@openai/agents';
37
35
  import OpenAI from 'openai';
38
36
  import * as ts from 'typescript';
39
37
  import ignore from 'ignore';
40
38
  import * as readline from 'readline';
41
39
  import { emitKeypressEvents, clearLine, cursorTo, createInterface } from 'readline';
40
+ import { lookup, extension } from 'mime-types';
41
+ import papaparse from 'papaparse';
42
42
  import { pathToFileURL } from 'url';
43
43
  import { EventEmitter } from 'events';
44
44
  import { Client } from 'pg';
@@ -58,7 +58,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
58
58
  * @generated
59
59
  * @see https://github.com/webgptorg/promptbook
60
60
  */
61
- const PROMPTBOOK_ENGINE_VERSION = '0.112.0-121';
61
+ const PROMPTBOOK_ENGINE_VERSION = '0.112.0-123';
62
62
  /**
63
63
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
64
64
  * Note: [πŸ’ž] Ignore a discrepancy between file name and entity name
@@ -4016,6 +4016,21 @@ function announcePauseTargetLabel(nextPauseTargetLabel) {
4016
4016
  function resetPauseTargetLabel() {
4017
4017
  setPauseTargetLabel(DEFAULT_PAUSE_TARGET_LABEL);
4018
4018
  }
4019
+ /**
4020
+ * Requests a pause from an external controller (e.g. the Ink UI).
4021
+ */
4022
+ function requestPause() {
4023
+ if (pauseState === 'RUNNING') {
4024
+ setPauseState('PAUSING');
4025
+ }
4026
+ }
4027
+ /**
4028
+ * Resumes execution from an external controller after a pause.
4029
+ */
4030
+ function requestResume() {
4031
+ setPauseState('RUNNING');
4032
+ resetPauseTargetLabel();
4033
+ }
4019
4034
 
4020
4035
  /**
4021
4036
  * Just says that the variable is not used but should be kept
@@ -38608,6 +38623,48 @@ function $initializeCoderFindRefactorCandidatesCommand(program) {
38608
38623
  // Note: [🟑] Code for CLI command [find-refactor-candidates](src/cli/cli-commands/coder/find-refactor-candidates.ts) should never be published outside of `@promptbook/cli`
38609
38624
  // Note: [πŸ’ž] Ignore a discrepancy between file name and entity name
38610
38625
 
38626
+ /**
38627
+ * Initializes `coder find-unwritten` command for Promptbook CLI utilities
38628
+ *
38629
+ * Note: `$` is used to indicate that this function is not a pure function - it registers a command in the CLI
38630
+ *
38631
+ * @private internal function of `promptbookCli`
38632
+ */
38633
+ function $initializeCoderFindUnwrittenCommand(program) {
38634
+ const command = program.command('find-unwritten');
38635
+ command.description('List all prompt sections that still need to be authored (contain @@@ placeholder)');
38636
+ command.option('--priority <minimum-priority>', 'Filter prompts by minimum priority level', parseIntOption$2, 0);
38637
+ command.action(handleActionErrors(async (cliOptions) => {
38638
+ const { priority = 0 } = cliOptions;
38639
+ // Note: Import the function dynamically to avoid loading heavy dependencies until needed
38640
+ const { findUnwrittenPrompts } = await Promise.resolve().then(function () { return findUnwrittenPrompts$1; });
38641
+ try {
38642
+ await findUnwrittenPrompts({ priority });
38643
+ }
38644
+ catch (error) {
38645
+ assertsError(error);
38646
+ console.error(colors.bgRed(`${error.name}`));
38647
+ console.error(colors.red(error.stack || error.message));
38648
+ return process.exit(1);
38649
+ }
38650
+ return process.exit(0);
38651
+ }));
38652
+ }
38653
+ /**
38654
+ * Parses an integer option value
38655
+ *
38656
+ * @private internal utility of `coder find-unwritten` command
38657
+ */
38658
+ function parseIntOption$2(value) {
38659
+ const parsed = parseInt(value, 10);
38660
+ if (isNaN(parsed)) {
38661
+ throw new Error(`Invalid number: ${value}`);
38662
+ }
38663
+ return parsed;
38664
+ }
38665
+ // Note: [🟑] Code for CLI command [find-unwritten](src/cli/cli-commands/coder/find-unwritten.ts) should never be published outside of `@promptbook/cli`
38666
+ // Note: [πŸ’ž] Ignore a discrepancy between file name and entity name
38667
+
38611
38668
  /**
38612
38669
  * Relative path to the root prompts directory used by Promptbook coder utilities.
38613
38670
  *
@@ -39514,8 +39571,10 @@ function $initializeCoderInitCommand(program) {
39514
39571
  - CODING_AGENT_GIT_SIGNING_KEY
39515
39572
  `));
39516
39573
  command.action(handleActionErrors(async () => {
39517
- const summary = await initializeCoderProjectConfiguration(process.cwd());
39574
+ const projectPath = process.cwd();
39575
+ const summary = await initializeCoderProjectConfiguration(projectPath);
39518
39576
  printInitializationSummary(summary);
39577
+ await generatePromptBoilerplate({ projectPath, filesCount: 5 });
39519
39578
  }));
39520
39579
  }
39521
39580
  /**
@@ -39607,11 +39666,12 @@ function $initializeCoderRunCommand(program) {
39607
39666
  `));
39608
39667
  command.option('--dry-run', 'Print unwritten prompts without executing', false);
39609
39668
  addPromptRunnerSelectionOptions(command);
39669
+ command.option('--agent <agent-book-path>', 'Path to a .book file whose compiled system message is prepended to each coding prompt');
39610
39670
  command.option('--context <context-or-file>', 'Append extra instructions either inline or from a file path relative to the current project');
39611
39671
  command.option('--test <test-command...>', 'Run a verification command after each prompt; quote it when the command itself contains top-level flags');
39612
39672
  command.option('--preserve-logs', 'Keep generated temp prompt/log artifacts after successful rounds for debugging and analytics', false);
39613
39673
  addPromptRunnerExecutionOptions(command);
39614
- command.option('--priority <minimum-priority>', 'Filter prompts by minimum priority level', parseIntOption, 0);
39674
+ command.option('--priority <minimum-priority>', 'Filter prompts by minimum priority level', parseIntOption$1, 0);
39615
39675
  command.option('--wait [duration]', spaceTrim$1(`
39616
39676
  Wait between prompt rounds.
39617
39677
  Without a value (default): waits for user confirmation before each prompt (interactive mode).
@@ -39622,8 +39682,8 @@ function $initializeCoderRunCommand(program) {
39622
39682
  command.option('--auto-migrate', 'Run testing-server database migrations automatically after each successfully processed prompt');
39623
39683
  command.option('--allow-destructive-auto-migrate', 'Allow auto-migrate even when heuristic SQL safety check flags destructive pending migrations');
39624
39684
  command.action(handleActionErrors(async (cliOptions) => {
39625
- const { dryRun, context, test, preserveLogs, priority, wait, autoMigrate, allowDestructiveAutoMigrate } = cliOptions;
39626
- const testCommand = normalizeCommandOptionValue(test);
39685
+ const { dryRun, agent, context, test, preserveLogs, priority, wait, autoMigrate, allowDestructiveAutoMigrate, } = cliOptions;
39686
+ const testCommand = normalizeCommandOptionValue$1(test);
39627
39687
  const runnerOptions = normalizePromptRunnerCliOptions(cliOptions, {
39628
39688
  isAgentRequired: !dryRun,
39629
39689
  });
@@ -39648,6 +39708,7 @@ function $initializeCoderRunCommand(program) {
39648
39708
  ignoreGitChanges: runnerOptions.ignoreGitChanges,
39649
39709
  agentName: runnerOptions.agentName,
39650
39710
  model: runnerOptions.model,
39711
+ agent,
39651
39712
  context,
39652
39713
  testCommand,
39653
39714
  preserveLogs,
@@ -39681,7 +39742,7 @@ function $initializeCoderRunCommand(program) {
39681
39742
  *
39682
39743
  * @private internal utility of `coder run` command
39683
39744
  */
39684
- function parseIntOption(value) {
39745
+ function parseIntOption$1(value) {
39685
39746
  const parsed = parseInt(value, 10);
39686
39747
  if (isNaN(parsed)) {
39687
39748
  throw new Error(`Invalid number: ${value}`);
@@ -39693,7 +39754,7 @@ function parseIntOption(value) {
39693
39754
  *
39694
39755
  * @private internal utility of `coder run` command
39695
39756
  */
39696
- function normalizeCommandOptionValue(value) {
39757
+ function normalizeCommandOptionValue$1(value) {
39697
39758
  if (value === undefined) {
39698
39759
  return undefined;
39699
39760
  }
@@ -39708,6 +39769,157 @@ function normalizeCommandOptionValue(value) {
39708
39769
  // Note: [🟑] Code for CLI command [run](src/cli/cli-commands/coder/run.ts) should never be published outside of `@promptbook/cli`
39709
39770
  // Note: [πŸ’ž] Ignore a discrepancy between file name and entity name
39710
39771
 
39772
+ /**
39773
+ * Default port used by `ptbk coder server`.
39774
+ *
39775
+ * @private internal constant of `ptbk coder server`
39776
+ */
39777
+ const DEFAULT_CODER_SERVER_PORT = '4441';
39778
+ /**
39779
+ * Initializes `coder server` command for Promptbook CLI utilities.
39780
+ *
39781
+ * Runs the same prompt processing logic as `ptbk coder run` but keeps the process alive
39782
+ * and serves a kanban web UI on the configured port.
39783
+ *
39784
+ * Note: `$` is used to indicate that this function is not a pure function - it registers a command in the CLI
39785
+ *
39786
+ * @private internal function of `promptbookCli`
39787
+ */
39788
+ function $initializeCoderServerCommand(program) {
39789
+ const command = program.command('server');
39790
+ command.description(spaceTrim$1(`
39791
+ Start a coder server that watches for prompts and serves a kanban web UI
39792
+
39793
+ ${PROMPT_RUNNER_DESCRIPTION}
39794
+
39795
+ Features:
39796
+ - Runs the same prompt processing as \`ptbk coder run\`
39797
+ - Does not exit when all prompts are done; polls for new prompt files instead
39798
+ - Serves a kanban board at http://localhost:<port> for visual progress tracking
39799
+ - Allows editing prompt files directly from the browser (Trello-style)
39800
+ - Play / pause button in the browser stays in sync with the CLI pause state
39801
+ - Press "p" in the terminal to pause / resume (same as \`ptbk coder run\`)
39802
+ `));
39803
+ command.addOption(new Option('--port <port>', 'Port to start the coder server on')
39804
+ .env('PTBK_CODER_SERVER_PORT')
39805
+ .default(DEFAULT_CODER_SERVER_PORT));
39806
+ command.option('--dry-run', 'Print unwritten prompts without executing', false);
39807
+ addPromptRunnerSelectionOptions(command);
39808
+ command.option('--agent <agent-book-path>', 'Path to a .book file whose compiled system message is prepended to each coding prompt');
39809
+ command.option('--context <context-or-file>', 'Append extra instructions either inline or from a file path relative to the current project');
39810
+ command.option('--test <test-command...>', 'Run a verification command after each prompt; quote it when the command itself contains top-level flags');
39811
+ command.option('--preserve-logs', 'Keep generated temp prompt/log artifacts after successful rounds for debugging and analytics', false);
39812
+ addPromptRunnerExecutionOptions(command);
39813
+ command.option('--priority <minimum-priority>', 'Filter prompts by minimum priority level', parseIntOption, 0);
39814
+ command.option('--wait [duration]', spaceTrim$1(`
39815
+ Wait between prompt rounds.
39816
+ Without a value (default): waits for user confirmation before each prompt (interactive mode).
39817
+ With a duration like 1h, 30m, 5s: waits that long between prompts to avoid hitting rate limits of the harness.
39818
+ `), true);
39819
+ command.option('--no-wait', 'Skip all waiting between prompts and run non-interactively');
39820
+ command.option('--auto-migrate', 'Run testing-server database migrations automatically after each successfully processed prompt');
39821
+ command.option('--allow-destructive-auto-migrate', 'Allow auto-migrate even when heuristic SQL safety check flags destructive pending migrations');
39822
+ command.action(handleActionErrors(async (cliOptions) => {
39823
+ const { port: rawPort, dryRun, agent, context, test, preserveLogs, priority, wait, autoMigrate, allowDestructiveAutoMigrate, } = cliOptions;
39824
+ const port = parseCoderServerPort(rawPort);
39825
+ const testCommand = normalizeCommandOptionValue(test);
39826
+ const runnerOptions = normalizePromptRunnerCliOptions(cliOptions, {
39827
+ isAgentRequired: !dryRun,
39828
+ });
39829
+ // [1] Parse the --wait option (same logic as `coder run`)
39830
+ let waitForUser = false;
39831
+ let waitBetweenPrompts = 0;
39832
+ if (wait === true) {
39833
+ waitForUser = true;
39834
+ }
39835
+ else if (typeof wait === 'string' && wait !== '') {
39836
+ waitBetweenPrompts = parseDuration(wait);
39837
+ }
39838
+ const runOptions = {
39839
+ port,
39840
+ dryRun,
39841
+ waitForUser,
39842
+ waitBetweenPrompts,
39843
+ noCommit: runnerOptions.noCommit,
39844
+ ignoreGitChanges: runnerOptions.ignoreGitChanges,
39845
+ agentName: runnerOptions.agentName,
39846
+ model: runnerOptions.model,
39847
+ agent,
39848
+ context,
39849
+ testCommand,
39850
+ preserveLogs,
39851
+ noUi: runnerOptions.noUi,
39852
+ thinkingLevel: runnerOptions.thinkingLevel,
39853
+ priority,
39854
+ normalizeLineEndings: runnerOptions.normalizeLineEndings,
39855
+ allowCredits: runnerOptions.allowCredits,
39856
+ autoMigrate,
39857
+ allowDestructiveAutoMigrate,
39858
+ autoPush: runnerOptions.autoPush,
39859
+ autoPull: runnerOptions.autoPull,
39860
+ };
39861
+ // Note: Import dynamically to avoid loading heavy dependencies until needed
39862
+ const { runCodexPromptsServer } = await Promise.resolve().then(function () { return runCodexPromptsServer$1; });
39863
+ try {
39864
+ await runCodexPromptsServer(runOptions);
39865
+ }
39866
+ catch (error) {
39867
+ assertsError(error);
39868
+ console.error(colors.bgRed(`${error.name}`));
39869
+ console.error(colors.red(error.stack || error.message));
39870
+ return process.exit(1);
39871
+ }
39872
+ return process.exit(0);
39873
+ }));
39874
+ }
39875
+ /**
39876
+ * Parses and validates the coder server port number.
39877
+ *
39878
+ * @private internal utility of `coder server` command
39879
+ */
39880
+ function parseCoderServerPort(rawPort) {
39881
+ const port = Number.parseInt(rawPort, 10);
39882
+ if (!Number.isInteger(port) || port <= 0 || port > NETWORK_LIMITS.MAX_PORT) {
39883
+ throw new NotAllowed(spaceTrim$1(`
39884
+ Invalid coder server port: \`${rawPort}\`.
39885
+
39886
+ Use \`--port\` or \`PTBK_CODER_SERVER_PORT\` with an integer between \`1\` and \`${NETWORK_LIMITS.MAX_PORT}\`.
39887
+ `));
39888
+ }
39889
+ return port;
39890
+ }
39891
+ /**
39892
+ * Parses an integer option value.
39893
+ *
39894
+ * @private internal utility of `coder server` command
39895
+ */
39896
+ function parseIntOption(value) {
39897
+ const parsed = parseInt(value, 10);
39898
+ if (isNaN(parsed)) {
39899
+ throw new Error(`Invalid number: ${value}`);
39900
+ }
39901
+ return parsed;
39902
+ }
39903
+ /**
39904
+ * Joins one Commander option that may be parsed either as a single string or a variadic token array.
39905
+ *
39906
+ * @private internal utility of `coder server` command
39907
+ */
39908
+ function normalizeCommandOptionValue(value) {
39909
+ if (value === undefined) {
39910
+ return undefined;
39911
+ }
39912
+ const parts = Array.isArray(value) ? value : [value];
39913
+ const normalizedValue = parts
39914
+ .map((part) => part.trim())
39915
+ .filter(Boolean)
39916
+ .join(' ')
39917
+ .trim();
39918
+ return normalizedValue === '' ? undefined : normalizedValue;
39919
+ }
39920
+ // Note: [🟑] Code for CLI command [server](src/cli/cli-commands/coder/server.ts) should never be published outside of `@promptbook/cli`
39921
+ // Note: [πŸ’ž] Ignore a discrepancy between file name and entity name
39922
+
39711
39923
  /**
39712
39924
  * Initializes `coder verify` command for Promptbook CLI utilities
39713
39925
  *
@@ -39779,7 +39991,9 @@ function $initializeCoderCommand(program) {
39779
39991
  - init: Initialize coder configuration in current project
39780
39992
  - generate-boilerplates: Generate prompt boilerplate files
39781
39993
  - find-refactor-candidates: Find files that need refactoring
39994
+ - find-unwritten: List prompt sections that still need to be authored
39782
39995
  - run: Run coding prompts with AI agents
39996
+ - server: Start a long-running coder server with a kanban web UI
39783
39997
  - verify: Verify completed prompts
39784
39998
  - find-fresh-emoji-tags: Find unused emoji tags
39785
39999
  `));
@@ -39787,7 +40001,9 @@ function $initializeCoderCommand(program) {
39787
40001
  $initializeCoderInitCommand(coderCommand);
39788
40002
  $initializeCoderGenerateBoilerplatesCommand(coderCommand);
39789
40003
  $initializeCoderFindRefactorCandidatesCommand(coderCommand);
40004
+ $initializeCoderFindUnwrittenCommand(coderCommand);
39790
40005
  $initializeCoderRunCommand(coderCommand);
40006
+ $initializeCoderServerCommand(coderCommand);
39791
40007
  $initializeCoderVerifyCommand(coderCommand);
39792
40008
  $initializeCoderFindFreshEmojiTagCommand(coderCommand);
39793
40009
  // If no subcommand is provided, show help
@@ -68623,6 +68839,303 @@ var findRefactorCandidates$1 = /*#__PURE__*/Object.freeze({
68623
68839
  findRefactorCandidates: findRefactorCandidates
68624
68840
  });
68625
68841
 
68842
+ /**
68843
+ * Checks whether a prompt section meets the minimum priority threshold.
68844
+ */
68845
+ function hasSufficientPriority(section, minimumPriority) {
68846
+ return section.priority >= minimumPriority;
68847
+ }
68848
+
68849
+ /**
68850
+ * Trims leading and trailing empty lines.
68851
+ */
68852
+ function trimEmptyEdges(lines) {
68853
+ let start = 0;
68854
+ while (start < lines.length) {
68855
+ const startLine = lines[start];
68856
+ if (startLine !== undefined && startLine.trim() !== '') {
68857
+ break;
68858
+ }
68859
+ start += 1;
68860
+ }
68861
+ let end = lines.length - 1;
68862
+ while (end >= start) {
68863
+ const endLine = lines[end];
68864
+ if (endLine !== undefined && endLine.trim() !== '') {
68865
+ break;
68866
+ }
68867
+ end -= 1;
68868
+ }
68869
+ return lines.slice(start, end + 1);
68870
+ }
68871
+
68872
+ /**
68873
+ * Extracts prompt lines without the status marker.
68874
+ */
68875
+ function buildPromptLinesWithoutStatus(file, section) {
68876
+ const lines = file.lines.slice(section.startLine, section.endLine + 1);
68877
+ if (section.statusLineIndex !== undefined) {
68878
+ const relativeIndex = section.statusLineIndex - section.startLine;
68879
+ if (relativeIndex >= 0 && relativeIndex < lines.length) {
68880
+ lines.splice(relativeIndex, 1);
68881
+ }
68882
+ }
68883
+ return trimEmptyEdges(lines);
68884
+ }
68885
+
68886
+ /**
68887
+ * Builds the prompt text sent to the agent runner.
68888
+ */
68889
+ function buildCodexPrompt(file, section) {
68890
+ const lines = buildPromptLinesWithoutStatus(file, section);
68891
+ for (let i = 0; i < lines.length; i++) {
68892
+ const line = lines[i];
68893
+ if (line === undefined || line.trim() === '') {
68894
+ continue;
68895
+ }
68896
+ lines[i] = line.replace(/^\[[^\]]+\]\s*/, '');
68897
+ break;
68898
+ }
68899
+ return lines.join(file.eol);
68900
+ }
68901
+
68902
+ /**
68903
+ * Checks whether a prompt section still needs authoring (contains "@@@").
68904
+ */
68905
+ function isPromptToBeWritten(file, section) {
68906
+ return buildCodexPrompt(file, section).includes('@@@');
68907
+ }
68908
+
68909
+ /**
68910
+ * Lists todo prompts across all files.
68911
+ */
68912
+ function listTodoPrompts(files) {
68913
+ const prompts = [];
68914
+ for (const file of files) {
68915
+ for (const section of file.sections) {
68916
+ if (section.status === 'todo') {
68917
+ prompts.push({ file, section });
68918
+ }
68919
+ }
68920
+ }
68921
+ return prompts;
68922
+ }
68923
+
68924
+ /**
68925
+ * Lists todo prompts that still contain authoring placeholders.
68926
+ */
68927
+ function listPromptsToBeWritten(files, minimumPriority = 0) {
68928
+ return listTodoPrompts(files).filter((prompt) => isPromptToBeWritten(prompt.file, prompt.section) && hasSufficientPriority(prompt.section, minimumPriority));
68929
+ }
68930
+
68931
+ /**
68932
+ * Parses a prompt markdown file into sections and metadata.
68933
+ */
68934
+ function parsePromptFile(filePath, content) {
68935
+ var _a, _b;
68936
+ const eol = content.includes('\r\n') ? '\r\n' : '\n';
68937
+ const hasFinalEol = content.endsWith('\n');
68938
+ const lines = content.split(/\r?\n/);
68939
+ const sections = [];
68940
+ let startLine = 0;
68941
+ let index = 0;
68942
+ for (let i = 0; i <= lines.length; i++) {
68943
+ const line = lines[i];
68944
+ const isSeparator = i < lines.length && line !== undefined && line.trim() === '---';
68945
+ const isEnd = i === lines.length;
68946
+ if (!isSeparator && !isEnd) {
68947
+ continue;
68948
+ }
68949
+ const endLine = i - 1;
68950
+ const firstNonEmptyLine = findFirstNonEmptyLine(lines, startLine, endLine);
68951
+ if (firstNonEmptyLine !== undefined) {
68952
+ const statusLine = (lines[firstNonEmptyLine] || '').trim();
68953
+ const parsedStatus = parseStatusLine(statusLine);
68954
+ const status = (_a = parsedStatus === null || parsedStatus === void 0 ? void 0 : parsedStatus.status) !== null && _a !== void 0 ? _a : 'not-ready';
68955
+ const priority = (_b = parsedStatus === null || parsedStatus === void 0 ? void 0 : parsedStatus.priority) !== null && _b !== void 0 ? _b : 0;
68956
+ sections.push({
68957
+ index,
68958
+ startLine,
68959
+ endLine,
68960
+ status,
68961
+ priority,
68962
+ statusLineIndex: parsedStatus ? firstNonEmptyLine : undefined,
68963
+ });
68964
+ index += 1;
68965
+ }
68966
+ startLine = i + 1;
68967
+ }
68968
+ return {
68969
+ path: filePath,
68970
+ name: basename(filePath),
68971
+ lines,
68972
+ eol,
68973
+ hasFinalEol,
68974
+ sections,
68975
+ };
68976
+ }
68977
+ /**
68978
+ * Parses a status line like "[ ] !!" or "[-]" or "[x] ~$0.65 21 minutes..." into status and priority.
68979
+ * For [x] done and [!] failed prompts, allow metadata after the status marker.
68980
+ */
68981
+ function parseStatusLine(line) {
68982
+ var _a, _b, _c, _d, _e;
68983
+ // For done prompts [x], allow any content after (for cost/time metadata)
68984
+ const doneMatch = line.match(/^\[(?<status>[xX])\]/);
68985
+ if (doneMatch) {
68986
+ return { status: 'done', priority: 0 };
68987
+ }
68988
+ // For failed prompts [!], allow any content after (for failure metadata)
68989
+ const failedMatch = line.match(/^\[(?<status>!)\]/);
68990
+ if (failedMatch) {
68991
+ return { status: 'failed', priority: 0 };
68992
+ }
68993
+ // For todo [ ] and not-ready [-], require clean end with optional priority markers
68994
+ const match = line.match(/^\[(?<status>[ -])\]\s*(?<priority>!*)\s*$/);
68995
+ if (!match) {
68996
+ return undefined;
68997
+ }
68998
+ const statusChar = (_b = (_a = match.groups) === null || _a === void 0 ? void 0 : _a.status) === null || _b === void 0 ? void 0 : _b.toLowerCase();
68999
+ let status;
69000
+ if (statusChar === '-') {
69001
+ status = 'not-ready';
69002
+ }
69003
+ else {
69004
+ status = 'todo';
69005
+ }
69006
+ const priority = status === 'todo' ? (_e = (_d = (_c = match.groups) === null || _c === void 0 ? void 0 : _c.priority) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0 : 0;
69007
+ return { status, priority };
69008
+ }
69009
+ /**
69010
+ * Finds the first non-empty line index between two bounds.
69011
+ */
69012
+ function findFirstNonEmptyLine(lines, startLine, endLine) {
69013
+ for (let i = startLine; i <= endLine; i++) {
69014
+ const line = lines[i];
69015
+ if (line !== undefined && line.trim() !== '') {
69016
+ return i;
69017
+ }
69018
+ }
69019
+ return undefined;
69020
+ }
69021
+
69022
+ /**
69023
+ * Loads and parses prompt files from the prompts directory.
69024
+ */
69025
+ async function loadPromptFiles(promptsDir) {
69026
+ const entries = await readdir(promptsDir, { withFileTypes: true });
69027
+ const files = entries
69028
+ .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.md'))
69029
+ .map((entry) => join(promptsDir, entry.name))
69030
+ .sort((a, b) => a.localeCompare(b));
69031
+ const promptFiles = [];
69032
+ for (const filePath of files) {
69033
+ const content = await readFile(filePath, 'utf-8');
69034
+ promptFiles.push(parsePromptFile(filePath, content));
69035
+ }
69036
+ return promptFiles;
69037
+ }
69038
+
69039
+ /**
69040
+ * Builds a display label using the prompt line number for easier navigation.
69041
+ */
69042
+ function buildPromptLabelForDisplay(file, section) {
69043
+ return `${relative(process.cwd(), file.path).replace(/\\/g, '/')}#${section.startLine + 1}`;
69044
+ }
69045
+
69046
+ /**
69047
+ * Extracts a short summary line from a prompt section.
69048
+ */
69049
+ function buildPromptSummary(file, section) {
69050
+ const lines = buildCodexPrompt(file, section).split(/\r?\n/);
69051
+ const firstLine = lines.find((line) => line.trim() !== '');
69052
+ return (firstLine === null || firstLine === void 0 ? void 0 : firstLine.trim()) || '(empty prompt)';
69053
+ }
69054
+
69055
+ /**
69056
+ * Prints the list of prompts that still need to be written.
69057
+ */
69058
+ function printPromptsToBeWritten(files, minimumPriority = 0) {
69059
+ const promptsToWrite = listPromptsToBeWritten(files, minimumPriority);
69060
+ let i = 0;
69061
+ for (const { file, section } of promptsToWrite) {
69062
+ const label = buildPromptLabelForDisplay(file, section);
69063
+ const summary = buildPromptSummary(file, section);
69064
+ console.info(` ${++i}) ${label}: ${summary}`);
69065
+ }
69066
+ }
69067
+
69068
+ /**
69069
+ * Prints the summary stats line.
69070
+ */
69071
+ function printStats(stats, minimumPriority = 0) {
69072
+ const priorityStats = minimumPriority > 0 ? ` | Priority <${minimumPriority}: ${stats.belowMinimumPriority}` : '';
69073
+ console.info(colors.cyan(`Done: ${stats.done} | For agent: ${stats.forAgent}${priorityStats} | To be written: ${stats.toBeWritten}`));
69074
+ }
69075
+
69076
+ /**
69077
+ * Summarizes prompt stats for the runner output.
69078
+ */
69079
+ function summarizePrompts(files, minimumPriority = 0) {
69080
+ const stats = { done: 0, forAgent: 0, belowMinimumPriority: 0, toBeWritten: 0 };
69081
+ for (const file of files) {
69082
+ for (const section of file.sections) {
69083
+ if (section.status === 'done') {
69084
+ stats.done += 1;
69085
+ }
69086
+ else if (section.status === 'todo') {
69087
+ const isAbovePriority = hasSufficientPriority(section, minimumPriority);
69088
+ if (isPromptToBeWritten(file, section)) {
69089
+ if (!isAbovePriority) {
69090
+ continue;
69091
+ }
69092
+ stats.toBeWritten += 1;
69093
+ }
69094
+ else if (isAbovePriority) {
69095
+ stats.forAgent += 1;
69096
+ }
69097
+ else {
69098
+ stats.belowMinimumPriority += 1;
69099
+ }
69100
+ }
69101
+ }
69102
+ }
69103
+ return stats;
69104
+ }
69105
+
69106
+ /**
69107
+ * Constant for prompts dir β€” mirrors the constant in `runCodexPrompts.ts`.
69108
+ */
69109
+ const PROMPTS_DIR$2 = join(process.cwd(), 'prompts');
69110
+ /**
69111
+ * Lists and prints all prompt sections that still need to be authored (contain `@@@` placeholder).
69112
+ *
69113
+ * Reuses the same filtering logic as `ptbk coder run --dry-run`.
69114
+ *
69115
+ * @returns the number of unwritten prompts found
69116
+ * @public exported from `@promptbook/cli`
69117
+ */
69118
+ async function findUnwrittenPrompts(options = {}) {
69119
+ const { priority = 0 } = options;
69120
+ const promptFiles = await loadPromptFiles(PROMPTS_DIR$2);
69121
+ const stats = summarizePrompts(promptFiles, priority);
69122
+ printStats(stats, priority);
69123
+ const unwrittenPrompts = listPromptsToBeWritten(promptFiles, priority);
69124
+ if (unwrittenPrompts.length === 0) {
69125
+ console.info(colors.green('All prompts are written β€” nothing to do.'));
69126
+ }
69127
+ else {
69128
+ console.info(colors.yellow(`Found ${unwrittenPrompts.length} prompt(s) that need to be written:`));
69129
+ printPromptsToBeWritten(promptFiles, priority);
69130
+ }
69131
+ return unwrittenPrompts.length;
69132
+ }
69133
+
69134
+ var findUnwrittenPrompts$1 = /*#__PURE__*/Object.freeze({
69135
+ __proto__: null,
69136
+ findUnwrittenPrompts: findUnwrittenPrompts
69137
+ });
69138
+
68626
69139
  /**
68627
69140
  * CLI usage text for this script.
68628
69141
  */
@@ -68966,6 +69479,29 @@ function formatPromptCount(count) {
68966
69479
  return `${count} prompt${count === 1 ? '' : 's'}`;
68967
69480
  }
68968
69481
 
69482
+ /**
69483
+ * Reads an optional agent `.book` file and compiles its system message for injection into coder prompts.
69484
+ *
69485
+ * Returns `undefined` when no agent path is provided.
69486
+ */
69487
+ async function resolveAgentSystemMessage(agentPath, currentWorkingDirectory) {
69488
+ if (!agentPath) {
69489
+ return undefined;
69490
+ }
69491
+ const resolvedAgentPath = resolve(currentWorkingDirectory, agentPath);
69492
+ const agentSource = await readFile(resolvedAgentPath, 'utf-8').catch((error) => {
69493
+ if (error.code === 'ENOENT' || error.code === 'EISDIR') {
69494
+ throw new NotFoundError(spaceTrim(`
69495
+ Agent book \`${agentPath}\` was not found or is not a file.
69496
+
69497
+ Pass a path to a \`.book\` file in \`--agent\`.
69498
+ `));
69499
+ }
69500
+ throw error;
69501
+ });
69502
+ return createAgentRunnerSystemMessage(agentSource);
69503
+ }
69504
+
68969
69505
  /**
68970
69506
  * Resolves optional coding context provided inline or via a file path.
68971
69507
  */
@@ -69008,104 +69544,6 @@ async function ensureWorkingTreeClean() {
69008
69544
  }
69009
69545
  }
69010
69546
 
69011
- /**
69012
- * Builds a display label using the prompt line number for easier navigation.
69013
- */
69014
- function buildPromptLabelForDisplay(file, section) {
69015
- return `${relative(process.cwd(), file.path).replace(/\\/g, '/')}#${section.startLine + 1}`;
69016
- }
69017
-
69018
- /**
69019
- * Trims leading and trailing empty lines.
69020
- */
69021
- function trimEmptyEdges(lines) {
69022
- let start = 0;
69023
- while (start < lines.length) {
69024
- const startLine = lines[start];
69025
- if (startLine !== undefined && startLine.trim() !== '') {
69026
- break;
69027
- }
69028
- start += 1;
69029
- }
69030
- let end = lines.length - 1;
69031
- while (end >= start) {
69032
- const endLine = lines[end];
69033
- if (endLine !== undefined && endLine.trim() !== '') {
69034
- break;
69035
- }
69036
- end -= 1;
69037
- }
69038
- return lines.slice(start, end + 1);
69039
- }
69040
-
69041
- /**
69042
- * Extracts prompt lines without the status marker.
69043
- */
69044
- function buildPromptLinesWithoutStatus(file, section) {
69045
- const lines = file.lines.slice(section.startLine, section.endLine + 1);
69046
- if (section.statusLineIndex !== undefined) {
69047
- const relativeIndex = section.statusLineIndex - section.startLine;
69048
- if (relativeIndex >= 0 && relativeIndex < lines.length) {
69049
- lines.splice(relativeIndex, 1);
69050
- }
69051
- }
69052
- return trimEmptyEdges(lines);
69053
- }
69054
-
69055
- /**
69056
- * Builds the prompt text sent to the agent runner.
69057
- */
69058
- function buildCodexPrompt(file, section) {
69059
- const lines = buildPromptLinesWithoutStatus(file, section);
69060
- for (let i = 0; i < lines.length; i++) {
69061
- const line = lines[i];
69062
- if (line === undefined || line.trim() === '') {
69063
- continue;
69064
- }
69065
- lines[i] = line.replace(/^\[[^\]]+\]\s*/, '');
69066
- break;
69067
- }
69068
- return lines.join(file.eol);
69069
- }
69070
-
69071
- /**
69072
- * Extracts a short summary line from a prompt section.
69073
- */
69074
- function buildPromptSummary(file, section) {
69075
- const lines = buildCodexPrompt(file, section).split(/\r?\n/);
69076
- const firstLine = lines.find((line) => line.trim() !== '');
69077
- return (firstLine === null || firstLine === void 0 ? void 0 : firstLine.trim()) || '(empty prompt)';
69078
- }
69079
-
69080
- /**
69081
- * Checks whether a prompt section meets the minimum priority threshold.
69082
- */
69083
- function hasSufficientPriority(section, minimumPriority) {
69084
- return section.priority >= minimumPriority;
69085
- }
69086
-
69087
- /**
69088
- * Checks whether a prompt section still needs authoring (contains "@@@").
69089
- */
69090
- function isPromptToBeWritten(file, section) {
69091
- return buildCodexPrompt(file, section).includes('@@@');
69092
- }
69093
-
69094
- /**
69095
- * Lists todo prompts across all files.
69096
- */
69097
- function listTodoPrompts(files) {
69098
- const prompts = [];
69099
- for (const file of files) {
69100
- for (const section of file.sections) {
69101
- if (section.status === 'todo') {
69102
- prompts.push({ file, section });
69103
- }
69104
- }
69105
- }
69106
- return prompts;
69107
- }
69108
-
69109
69547
  /**
69110
69548
  * Lists todo prompts that are ready to run (no authoring placeholders).
69111
69549
  */
@@ -69138,142 +69576,6 @@ function listUpcomingTasks(files, minimumPriority = 0) {
69138
69576
  }));
69139
69577
  }
69140
69578
 
69141
- /**
69142
- * Parses a prompt markdown file into sections and metadata.
69143
- */
69144
- function parsePromptFile(filePath, content) {
69145
- var _a, _b;
69146
- const eol = content.includes('\r\n') ? '\r\n' : '\n';
69147
- const hasFinalEol = content.endsWith('\n');
69148
- const lines = content.split(/\r?\n/);
69149
- const sections = [];
69150
- let startLine = 0;
69151
- let index = 0;
69152
- for (let i = 0; i <= lines.length; i++) {
69153
- const line = lines[i];
69154
- const isSeparator = i < lines.length && line !== undefined && line.trim() === '---';
69155
- const isEnd = i === lines.length;
69156
- if (!isSeparator && !isEnd) {
69157
- continue;
69158
- }
69159
- const endLine = i - 1;
69160
- const firstNonEmptyLine = findFirstNonEmptyLine(lines, startLine, endLine);
69161
- if (firstNonEmptyLine !== undefined) {
69162
- const statusLine = (lines[firstNonEmptyLine] || '').trim();
69163
- const parsedStatus = parseStatusLine(statusLine);
69164
- const status = (_a = parsedStatus === null || parsedStatus === void 0 ? void 0 : parsedStatus.status) !== null && _a !== void 0 ? _a : 'not-ready';
69165
- const priority = (_b = parsedStatus === null || parsedStatus === void 0 ? void 0 : parsedStatus.priority) !== null && _b !== void 0 ? _b : 0;
69166
- sections.push({
69167
- index,
69168
- startLine,
69169
- endLine,
69170
- status,
69171
- priority,
69172
- statusLineIndex: parsedStatus ? firstNonEmptyLine : undefined,
69173
- });
69174
- index += 1;
69175
- }
69176
- startLine = i + 1;
69177
- }
69178
- return {
69179
- path: filePath,
69180
- name: basename(filePath),
69181
- lines,
69182
- eol,
69183
- hasFinalEol,
69184
- sections,
69185
- };
69186
- }
69187
- /**
69188
- * Parses a status line like "[ ] !!" or "[-]" or "[x] ~$0.65 21 minutes..." into status and priority.
69189
- * For [x] done and [!] failed prompts, allow metadata after the status marker.
69190
- */
69191
- function parseStatusLine(line) {
69192
- var _a, _b, _c, _d, _e;
69193
- // For done prompts [x], allow any content after (for cost/time metadata)
69194
- const doneMatch = line.match(/^\[(?<status>[xX])\]/);
69195
- if (doneMatch) {
69196
- return { status: 'done', priority: 0 };
69197
- }
69198
- // For failed prompts [!], allow any content after (for failure metadata)
69199
- const failedMatch = line.match(/^\[(?<status>!)\]/);
69200
- if (failedMatch) {
69201
- return { status: 'failed', priority: 0 };
69202
- }
69203
- // For todo [ ] and not-ready [-], require clean end with optional priority markers
69204
- const match = line.match(/^\[(?<status>[ -])\]\s*(?<priority>!*)\s*$/);
69205
- if (!match) {
69206
- return undefined;
69207
- }
69208
- const statusChar = (_b = (_a = match.groups) === null || _a === void 0 ? void 0 : _a.status) === null || _b === void 0 ? void 0 : _b.toLowerCase();
69209
- let status;
69210
- if (statusChar === '-') {
69211
- status = 'not-ready';
69212
- }
69213
- else {
69214
- status = 'todo';
69215
- }
69216
- const priority = status === 'todo' ? (_e = (_d = (_c = match.groups) === null || _c === void 0 ? void 0 : _c.priority) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0 : 0;
69217
- return { status, priority };
69218
- }
69219
- /**
69220
- * Finds the first non-empty line index between two bounds.
69221
- */
69222
- function findFirstNonEmptyLine(lines, startLine, endLine) {
69223
- for (let i = startLine; i <= endLine; i++) {
69224
- const line = lines[i];
69225
- if (line !== undefined && line.trim() !== '') {
69226
- return i;
69227
- }
69228
- }
69229
- return undefined;
69230
- }
69231
-
69232
- /**
69233
- * Loads and parses prompt files from the prompts directory.
69234
- */
69235
- async function loadPromptFiles(promptsDir) {
69236
- const entries = await readdir(promptsDir, { withFileTypes: true });
69237
- const files = entries
69238
- .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.md'))
69239
- .map((entry) => join(promptsDir, entry.name))
69240
- .sort((a, b) => a.localeCompare(b));
69241
- const promptFiles = [];
69242
- for (const filePath of files) {
69243
- const content = await readFile(filePath, 'utf-8');
69244
- promptFiles.push(parsePromptFile(filePath, content));
69245
- }
69246
- return promptFiles;
69247
- }
69248
-
69249
- /**
69250
- * Lists todo prompts that still contain authoring placeholders.
69251
- */
69252
- function listPromptsToBeWritten(files, minimumPriority = 0) {
69253
- return listTodoPrompts(files).filter((prompt) => isPromptToBeWritten(prompt.file, prompt.section) && hasSufficientPriority(prompt.section, minimumPriority));
69254
- }
69255
-
69256
- /**
69257
- * Prints the list of prompts that still need to be written.
69258
- */
69259
- function printPromptsToBeWritten(files, minimumPriority = 0) {
69260
- const promptsToWrite = listPromptsToBeWritten(files, minimumPriority);
69261
- let i = 0;
69262
- for (const { file, section } of promptsToWrite) {
69263
- const label = buildPromptLabelForDisplay(file, section);
69264
- const summary = buildPromptSummary(file, section);
69265
- console.info(` ${++i}) ${label}: ${summary}`);
69266
- }
69267
- }
69268
-
69269
- /**
69270
- * Prints the summary stats line.
69271
- */
69272
- function printStats(stats, minimumPriority = 0) {
69273
- const priorityStats = minimumPriority > 0 ? ` | Priority <${minimumPriority}: ${stats.belowMinimumPriority}` : '';
69274
- console.info(colors.cyan(`Done: ${stats.done} | For agent: ${stats.forAgent}${priorityStats} | To be written: ${stats.toBeWritten}`));
69275
- }
69276
-
69277
69579
  /**
69278
69580
  * Groups upcoming tasks by priority, high to low.
69279
69581
  */
@@ -69311,36 +69613,6 @@ function printUpcomingTasks(tasks) {
69311
69613
  }
69312
69614
  }
69313
69615
 
69314
- /**
69315
- * Summarizes prompt stats for the runner output.
69316
- */
69317
- function summarizePrompts(files, minimumPriority = 0) {
69318
- const stats = { done: 0, forAgent: 0, belowMinimumPriority: 0, toBeWritten: 0 };
69319
- for (const file of files) {
69320
- for (const section of file.sections) {
69321
- if (section.status === 'done') {
69322
- stats.done += 1;
69323
- }
69324
- else if (section.status === 'todo') {
69325
- const isAbovePriority = hasSufficientPriority(section, minimumPriority);
69326
- if (isPromptToBeWritten(file, section)) {
69327
- if (!isAbovePriority) {
69328
- continue;
69329
- }
69330
- stats.toBeWritten += 1;
69331
- }
69332
- else if (isAbovePriority) {
69333
- stats.forAgent += 1;
69334
- }
69335
- else {
69336
- stats.belowMinimumPriority += 1;
69337
- }
69338
- }
69339
- }
69340
- }
69341
- return stats;
69342
- }
69343
-
69344
69616
  /**
69345
69617
  * Waits for the user to press Enter before continuing.
69346
69618
  */
@@ -70965,9 +71237,14 @@ async function writePromptFile(file) {
70965
71237
  *
70966
71238
  * @private function of runCodexPrompts
70967
71239
  */
70968
- async function runPromptRound({ options, runner, runnerMetadata, nextPrompt, promptLabel, resolvedCoderContext, isRichUiEnabled, progressDisplay, uiHandle, waitForRequestedPause, }) {
71240
+ async function runPromptRound({ options, runner, runnerMetadata, nextPrompt, promptLabel, resolvedCoderContext, resolvedAgentSystemMessage, isRichUiEnabled, progressDisplay, uiHandle, waitForRequestedPause, }) {
70969
71241
  const commitMessage = buildCommitMessage(nextPrompt.file, nextPrompt.section);
70970
- const codexPrompt = appendCoderContext(buildCodexPrompt(nextPrompt.file, nextPrompt.section), resolvedCoderContext);
71242
+ const taskPrompt = buildCodexPrompt(nextPrompt.file, nextPrompt.section);
71243
+ // Prepend agent system message before the task so the harness sees agent instructions first
71244
+ const promptWithAgent = resolvedAgentSystemMessage
71245
+ ? `${resolvedAgentSystemMessage.trim()}\n\n${taskPrompt}`
71246
+ : taskPrompt;
71247
+ const codexPrompt = appendCoderContext(promptWithAgent, resolvedCoderContext);
70971
71248
  const scriptPath = buildScriptPath(nextPrompt.file, nextPrompt.section);
70972
71249
  setPromptRoundRunningState({ isRichUiEnabled, promptLabel, scriptPath, uiHandle });
70973
71250
  await waitForRequestedPause({
@@ -71200,6 +71477,7 @@ async function runCodexPrompts(providedOptions) {
71200
71477
  startPauseListenerIfNeeded(isRichUiEnabled);
71201
71478
  try {
71202
71479
  const resolvedCoderContext = await resolveCoderContext(options.context, process.cwd());
71480
+ const resolvedAgentSystemMessage = await resolveAgentSystemMessage(options.agent, process.cwd());
71203
71481
  if (await runDryRunIfRequested(options)) {
71204
71482
  return;
71205
71483
  }
@@ -71239,7 +71517,13 @@ async function runCodexPrompts(providedOptions) {
71239
71517
  minimumPriority: options.priority,
71240
71518
  isRichUiEnabled,
71241
71519
  }));
71242
- if (finishWhenNoPromptIsAvailable(promptQueueSnapshot, isRichUiEnabled, uiHandle)) {
71520
+ if (!promptQueueSnapshot.nextPrompt) {
71521
+ if (options.keepAlive) {
71522
+ announceKeepAliveStatus(promptQueueSnapshot, isRichUiEnabled, uiHandle);
71523
+ await new Promise((resolve) => setTimeout(resolve, KEEP_ALIVE_POLL_INTERVAL_MS));
71524
+ continue;
71525
+ }
71526
+ finishWhenNoPromptIsAvailable(promptQueueSnapshot, isRichUiEnabled, uiHandle);
71243
71527
  return;
71244
71528
  }
71245
71529
  const nextPrompt = promptQueueSnapshot.nextPrompt;
@@ -71278,6 +71562,7 @@ async function runCodexPrompts(providedOptions) {
71278
71562
  nextPrompt,
71279
71563
  promptLabel,
71280
71564
  resolvedCoderContext,
71565
+ resolvedAgentSystemMessage,
71281
71566
  isRichUiEnabled,
71282
71567
  progressDisplay,
71283
71568
  uiHandle,
@@ -71453,6 +71738,19 @@ function finishWhenNoPromptIsAvailable(promptQueueSnapshot, isRichUiEnabled, uiH
71453
71738
  }
71454
71739
  return true;
71455
71740
  }
71741
+ /**
71742
+ * Updates the UI status message while waiting for new prompts in keepAlive server mode.
71743
+ */
71744
+ function announceKeepAliveStatus(promptQueueSnapshot, isRichUiEnabled, uiHandle) {
71745
+ const message = promptQueueSnapshot.stats.toBeWritten > 0
71746
+ ? 'No prompts ready for agent. Watching for changes...'
71747
+ : 'All prompts are done. Watching for changes...';
71748
+ uiHandle === null || uiHandle === void 0 ? void 0 : uiHandle.state.setStatusMessage(message);
71749
+ uiHandle === null || uiHandle === void 0 ? void 0 : uiHandle.state.setPhase('waiting');
71750
+ if (!isRichUiEnabled) {
71751
+ console.info(colors.gray(message));
71752
+ }
71753
+ }
71456
71754
  /**
71457
71755
  * Updates UI state and plain-console output for the terminal completion message.
71458
71756
  */
@@ -71493,6 +71791,10 @@ async function waitForPromptConfirmationIfNeeded(options) {
71493
71791
  * Countdown update interval for the between-rounds wait display.
71494
71792
  */
71495
71793
  const WAIT_COUNTDOWN_UPDATE_INTERVAL_MS = 30000;
71794
+ /**
71795
+ * Polling interval when in keepAlive server mode and no runnable prompts are available.
71796
+ */
71797
+ const KEEP_ALIVE_POLL_INTERVAL_MS = 5000;
71496
71798
  /**
71497
71799
  * Waits the configured time between prompt rounds to avoid hitting harness rate limits.
71498
71800
  * Does nothing when `waitBetweenPrompts` is zero.
@@ -71538,6 +71840,780 @@ var runCodexPrompts$1 = /*#__PURE__*/Object.freeze({
71538
71840
  runCodexPrompts: runCodexPrompts
71539
71841
  });
71540
71842
 
71843
+ /**
71844
+ * Overwrites the body of one prompt section with new content, preserving the status line.
71845
+ *
71846
+ * The `newContent` string is the prompt text without the status marker.
71847
+ * The status line (`[ ]`, `[x]`, `[!]`, `[-]`) is kept intact.
71848
+ *
71849
+ * @private internal utility of `ptbk coder server`
71850
+ */
71851
+ async function updatePromptSection(filePath, sectionIndex, newContent) {
71852
+ var _a;
71853
+ const rawContent = await readFile(filePath, 'utf-8');
71854
+ const promptFile = parsePromptFile(filePath, rawContent);
71855
+ const section = promptFile.sections.find((s) => s.index === sectionIndex);
71856
+ if (!section) {
71857
+ throw new Error(`Section ${sectionIndex} not found in file: ${filePath}`);
71858
+ }
71859
+ // Lines before the status line (usually empty lines at section start)
71860
+ const linesBeforeStatus = section.statusLineIndex !== undefined
71861
+ ? promptFile.lines.slice(section.startLine, section.statusLineIndex)
71862
+ : [];
71863
+ // The status line itself (preserved exactly)
71864
+ const statusLineContent = section.statusLineIndex !== undefined ? [promptFile.lines[section.statusLineIndex]] : [];
71865
+ // Split the new content and trim trailing blank lines
71866
+ const newContentLines = newContent.split(/\r?\n/);
71867
+ while (newContentLines.length > 0 && ((_a = newContentLines[newContentLines.length - 1]) === null || _a === void 0 ? void 0 : _a.trim()) === '') {
71868
+ newContentLines.pop();
71869
+ }
71870
+ // Build the reconstructed section lines
71871
+ const newSectionLines = [
71872
+ ...linesBeforeStatus,
71873
+ ...statusLineContent,
71874
+ ...(statusLineContent.length > 0 ? [''] : []),
71875
+ ...newContentLines,
71876
+ ];
71877
+ // Splice the new section lines into the full file line array
71878
+ const updatedLines = [
71879
+ ...promptFile.lines.slice(0, section.startLine),
71880
+ ...newSectionLines,
71881
+ ...promptFile.lines.slice(section.endLine + 1),
71882
+ ];
71883
+ const updatedContent = updatedLines.join(promptFile.eol) + (promptFile.hasFinalEol ? promptFile.eol : '');
71884
+ await writeFile(filePath, updatedContent, 'utf-8');
71885
+ }
71886
+ // Note: [🟑] Code for CLI command [coder server](scripts/run-codex-prompts/server/updatePromptSection.ts) should never be published outside of `@promptbook/cli`
71887
+
71888
+ /**
71889
+ * HTML source for the coder server kanban UI.
71890
+ *
71891
+ * The canonical source lives in `apps/coder-server/index.html`.
71892
+ * Keep both files in sync when updating the frontend.
71893
+ *
71894
+ * @private internal constant of `ptbk coder server`
71895
+ */
71896
+ const CODER_SERVER_HTML = `<!DOCTYPE html>
71897
+ <html lang="en">
71898
+ <head>
71899
+ <meta charset="UTF-8">
71900
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
71901
+ <title>Ptbk Coder Server</title>
71902
+ <style>
71903
+ * { box-sizing: border-box; margin: 0; padding: 0; }
71904
+ body {
71905
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
71906
+ background: #f4f5f7;
71907
+ color: #172b4d;
71908
+ min-height: 100vh;
71909
+ }
71910
+
71911
+ header {
71912
+ background: #0052cc;
71913
+ color: white;
71914
+ padding: 12px 20px;
71915
+ display: flex;
71916
+ align-items: center;
71917
+ gap: 12px;
71918
+ position: sticky;
71919
+ top: 0;
71920
+ z-index: 10;
71921
+ box-shadow: 0 2px 8px rgba(0,0,0,0.2);
71922
+ }
71923
+ header h1 { font-size: 17px; font-weight: 700; flex-shrink: 0; }
71924
+
71925
+ .status-badge {
71926
+ padding: 3px 10px;
71927
+ border-radius: 12px;
71928
+ font-size: 11px;
71929
+ font-weight: 700;
71930
+ letter-spacing: 0.5px;
71931
+ text-transform: uppercase;
71932
+ flex-shrink: 0;
71933
+ }
71934
+ .status-RUNNING { background: #00875a; color: white; }
71935
+ .status-PAUSING { background: #ff8b00; color: white; }
71936
+ .status-PAUSED { background: #bf2600; color: white; }
71937
+
71938
+ #pause-label {
71939
+ font-size: 12px;
71940
+ color: rgba(255,255,255,0.75);
71941
+ flex: 1;
71942
+ min-width: 0;
71943
+ overflow: hidden;
71944
+ text-overflow: ellipsis;
71945
+ white-space: nowrap;
71946
+ }
71947
+
71948
+ .btn {
71949
+ padding: 6px 14px;
71950
+ border: none;
71951
+ border-radius: 4px;
71952
+ cursor: pointer;
71953
+ font-size: 13px;
71954
+ font-weight: 600;
71955
+ transition: opacity 0.15s;
71956
+ flex-shrink: 0;
71957
+ }
71958
+ .btn:hover { opacity: 0.85; }
71959
+ .btn-pause { background: #ffc400; color: #172b4d; }
71960
+ .btn-resume { background: #00875a; color: white; }
71961
+
71962
+ .board {
71963
+ display: flex;
71964
+ gap: 14px;
71965
+ padding: 16px;
71966
+ overflow-x: auto;
71967
+ min-height: calc(100vh - 52px);
71968
+ align-items: flex-start;
71969
+ }
71970
+
71971
+ .column {
71972
+ background: #ebecf0;
71973
+ border-radius: 8px;
71974
+ padding: 10px;
71975
+ min-width: 250px;
71976
+ width: 270px;
71977
+ flex-shrink: 0;
71978
+ }
71979
+
71980
+ .column-header {
71981
+ font-size: 12px;
71982
+ font-weight: 700;
71983
+ text-transform: uppercase;
71984
+ letter-spacing: 0.6px;
71985
+ color: #5e6c84;
71986
+ margin-bottom: 10px;
71987
+ display: flex;
71988
+ align-items: center;
71989
+ justify-content: space-between;
71990
+ }
71991
+
71992
+ .column-count {
71993
+ background: #dfe1e6;
71994
+ border-radius: 10px;
71995
+ padding: 1px 7px;
71996
+ font-size: 11px;
71997
+ color: #5e6c84;
71998
+ }
71999
+
72000
+ .column-cards { min-height: 40px; }
72001
+
72002
+ .card {
72003
+ background: white;
72004
+ border-radius: 6px;
72005
+ padding: 10px 12px;
72006
+ margin-bottom: 8px;
72007
+ box-shadow: 0 1px 3px rgba(0,0,0,0.08);
72008
+ cursor: pointer;
72009
+ transition: box-shadow 0.15s, transform 0.1s;
72010
+ border-left: 3px solid transparent;
72011
+ }
72012
+ .card:hover {
72013
+ box-shadow: 0 4px 10px rgba(0,0,0,0.14);
72014
+ transform: translateY(-1px);
72015
+ }
72016
+ .card-todo { border-left-color: #0052cc; }
72017
+ .card-not-ready { border-left-color: #8993a4; }
72018
+ .card-done { border-left-color: #00875a; }
72019
+ .card-failed { border-left-color: #bf2600; }
72020
+
72021
+ .card-file {
72022
+ font-size: 10px;
72023
+ color: #8993a4;
72024
+ margin-bottom: 5px;
72025
+ font-weight: 500;
72026
+ }
72027
+
72028
+ .card-summary {
72029
+ font-size: 13px;
72030
+ line-height: 1.5;
72031
+ color: #172b4d;
72032
+ word-break: break-word;
72033
+ white-space: pre-wrap;
72034
+ max-height: 78px;
72035
+ overflow: hidden;
72036
+ display: -webkit-box;
72037
+ -webkit-line-clamp: 4;
72038
+ -webkit-box-orient: vertical;
72039
+ }
72040
+
72041
+ .card-priority {
72042
+ margin-top: 6px;
72043
+ color: #ff8b00;
72044
+ font-size: 11px;
72045
+ font-weight: 700;
72046
+ }
72047
+
72048
+ .card-edit-hint {
72049
+ font-size: 10px;
72050
+ color: #c1c7d0;
72051
+ margin-top: 6px;
72052
+ display: none;
72053
+ }
72054
+ .card:hover .card-edit-hint { display: block; }
72055
+
72056
+ .empty-column {
72057
+ color: #b3bac5;
72058
+ font-size: 12px;
72059
+ padding: 10px 4px;
72060
+ text-align: center;
72061
+ }
72062
+
72063
+ .modal-overlay {
72064
+ position: fixed;
72065
+ inset: 0;
72066
+ background: rgba(9,30,66,0.54);
72067
+ display: flex;
72068
+ align-items: flex-start;
72069
+ justify-content: center;
72070
+ padding: 60px 16px 16px;
72071
+ z-index: 100;
72072
+ animation: fadeIn 0.1s ease;
72073
+ }
72074
+ .modal-overlay.hidden { display: none; }
72075
+
72076
+ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
72077
+
72078
+ .modal {
72079
+ background: white;
72080
+ border-radius: 8px;
72081
+ width: 100%;
72082
+ max-width: 620px;
72083
+ padding: 20px;
72084
+ box-shadow: 0 8px 32px rgba(0,0,0,0.25);
72085
+ animation: slideIn 0.15s ease;
72086
+ }
72087
+ @keyframes slideIn { from { transform: translateY(-8px); opacity: 0; } to { transform: none; opacity: 1; } }
72088
+
72089
+ .modal-header {
72090
+ display: flex;
72091
+ align-items: flex-start;
72092
+ justify-content: space-between;
72093
+ margin-bottom: 14px;
72094
+ gap: 12px;
72095
+ }
72096
+
72097
+ .modal-meta { flex: 1; min-width: 0; }
72098
+ .modal-file { font-size: 11px; color: #8993a4; margin-bottom: 4px; }
72099
+ .modal-section-label { font-size: 13px; font-weight: 600; color: #172b4d; }
72100
+
72101
+ .modal-status {
72102
+ font-size: 11px;
72103
+ font-weight: 700;
72104
+ padding: 2px 8px;
72105
+ border-radius: 10px;
72106
+ text-transform: uppercase;
72107
+ letter-spacing: 0.4px;
72108
+ flex-shrink: 0;
72109
+ }
72110
+ .status-todo { background: #deebff; color: #0052cc; }
72111
+ .status-not-ready { background: #f4f5f7; color: #5e6c84; }
72112
+ .status-done { background: #e3fcef; color: #006644; }
72113
+ .status-failed { background: #ffebe6; color: #bf2600; }
72114
+
72115
+ .modal-close {
72116
+ background: none;
72117
+ border: none;
72118
+ color: #8993a4;
72119
+ cursor: pointer;
72120
+ font-size: 18px;
72121
+ padding: 0 4px;
72122
+ line-height: 1;
72123
+ flex-shrink: 0;
72124
+ }
72125
+ .modal-close:hover { color: #172b4d; }
72126
+
72127
+ textarea {
72128
+ width: 100%;
72129
+ min-height: 220px;
72130
+ font-family: 'SFMono-Regular', 'Consolas', 'Courier New', monospace;
72131
+ font-size: 13px;
72132
+ border: 2px solid #dfe1e6;
72133
+ border-radius: 4px;
72134
+ padding: 10px 12px;
72135
+ resize: vertical;
72136
+ line-height: 1.65;
72137
+ color: #172b4d;
72138
+ transition: border-color 0.15s;
72139
+ }
72140
+ textarea:focus {
72141
+ outline: none;
72142
+ border-color: #0052cc;
72143
+ box-shadow: 0 0 0 3px rgba(0,82,204,0.12);
72144
+ }
72145
+
72146
+ .modal-hint {
72147
+ font-size: 11px;
72148
+ color: #8993a4;
72149
+ margin-top: 6px;
72150
+ }
72151
+
72152
+ .modal-actions {
72153
+ display: flex;
72154
+ gap: 8px;
72155
+ margin-top: 14px;
72156
+ justify-content: flex-end;
72157
+ }
72158
+
72159
+ .btn-save { background: #0052cc; color: white; }
72160
+ .btn-cancel { background: #f4f5f7; color: #172b4d; }
72161
+ .btn-cancel:hover { background: #ebecf0; opacity: 1; }
72162
+
72163
+ .error-banner {
72164
+ background: #ffebe6;
72165
+ border-bottom: 2px solid #bf2600;
72166
+ color: #bf2600;
72167
+ padding: 8px 20px;
72168
+ font-size: 13px;
72169
+ font-weight: 500;
72170
+ }
72171
+ .error-banner.hidden { display: none; }
72172
+ </style>
72173
+ </head>
72174
+ <body>
72175
+
72176
+ <div id="error-banner" class="error-banner hidden"></div>
72177
+
72178
+ <header>
72179
+ <h1>&#128295; Ptbk Coder Server</h1>
72180
+ <span id="status-badge" class="status-badge status-RUNNING">RUNNING</span>
72181
+ <span id="pause-label"></span>
72182
+ <button id="toggle-btn" class="btn btn-pause">&#9646;&#9646; Pause</button>
72183
+ </header>
72184
+
72185
+ <div class="board">
72186
+ <div class="column">
72187
+ <div class="column-header">
72188
+ To Do
72189
+ <span class="column-count" id="count-todo">0</span>
72190
+ </div>
72191
+ <div class="column-cards" id="cards-todo">
72192
+ <div class="empty-column">Loading&hellip;</div>
72193
+ </div>
72194
+ </div>
72195
+
72196
+ <div class="column">
72197
+ <div class="column-header">
72198
+ Not Ready
72199
+ <span class="column-count" id="count-not-ready">0</span>
72200
+ </div>
72201
+ <div class="column-cards" id="cards-not-ready"></div>
72202
+ </div>
72203
+
72204
+ <div class="column">
72205
+ <div class="column-header">
72206
+ Done
72207
+ <span class="column-count" id="count-done">0</span>
72208
+ </div>
72209
+ <div class="column-cards" id="cards-done"></div>
72210
+ </div>
72211
+
72212
+ <div class="column">
72213
+ <div class="column-header">
72214
+ Failed
72215
+ <span class="column-count" id="count-failed">0</span>
72216
+ </div>
72217
+ <div class="column-cards" id="cards-failed"></div>
72218
+ </div>
72219
+ </div>
72220
+
72221
+ <div class="modal-overlay hidden" id="modal-overlay">
72222
+ <div class="modal">
72223
+ <div class="modal-header">
72224
+ <div class="modal-meta">
72225
+ <div class="modal-file" id="modal-file"></div>
72226
+ <div class="modal-section-label" id="modal-section-label"></div>
72227
+ </div>
72228
+ <span class="modal-status" id="modal-status-badge"></span>
72229
+ <button class="modal-close" onclick="closeModal()" title="Close (Esc)">&#x2715;</button>
72230
+ </div>
72231
+
72232
+ <textarea id="modal-content" placeholder="Prompt content&hellip;"></textarea>
72233
+ <div class="modal-hint">Tip: press Ctrl+Enter to save, Esc to cancel.</div>
72234
+
72235
+ <div class="modal-actions">
72236
+ <button class="btn btn-cancel" onclick="closeModal()">Cancel</button>
72237
+ <button class="btn btn-save" onclick="saveModal()">Save</button>
72238
+ </div>
72239
+ </div>
72240
+ </div>
72241
+
72242
+ <script>
72243
+ 'use strict';
72244
+
72245
+ let modalState = null;
72246
+ let lastPauseState = 'RUNNING';
72247
+
72248
+ function showError(msg) {
72249
+ const banner = document.getElementById('error-banner');
72250
+ banner.textContent = '\\u26a0 ' + msg;
72251
+ banner.classList.remove('hidden');
72252
+ clearTimeout(banner._timer);
72253
+ banner._timer = setTimeout(() => banner.classList.add('hidden'), 6000);
72254
+ }
72255
+
72256
+ function escapeHtml(str) {
72257
+ const d = document.createElement('div');
72258
+ d.textContent = String(str);
72259
+ return d.innerHTML;
72260
+ }
72261
+
72262
+ async function fetchStatus() {
72263
+ try {
72264
+ const res = await fetch('/api/status');
72265
+ if (!res.ok) { showError('Status API error: ' + res.status); return; }
72266
+ const data = await res.json();
72267
+
72268
+ lastPauseState = data.pauseState;
72269
+
72270
+ const badge = document.getElementById('status-badge');
72271
+ badge.textContent = data.pauseState;
72272
+ badge.className = 'status-badge status-' + data.pauseState;
72273
+
72274
+ const btn = document.getElementById('toggle-btn');
72275
+ const label = document.getElementById('pause-label');
72276
+
72277
+ if (data.pauseState === 'RUNNING') {
72278
+ btn.textContent = '\\u23f8 Pause';
72279
+ btn.className = 'btn btn-pause';
72280
+ label.textContent = '';
72281
+ } else if (data.pauseState === 'PAUSING') {
72282
+ btn.textContent = '\\u23f5 Resume';
72283
+ btn.className = 'btn btn-resume';
72284
+ label.textContent = 'Pausing before: ' + (data.pauseTargetLabel || '\\u2026');
72285
+ } else {
72286
+ btn.textContent = '\\u23f5 Resume';
72287
+ btn.className = 'btn btn-resume';
72288
+ label.textContent = 'Paused before: ' + (data.pauseTargetLabel || '\\u2026');
72289
+ }
72290
+ } catch (e) {
72291
+ showError('Could not reach coder server: ' + e.message);
72292
+ }
72293
+ }
72294
+
72295
+ async function fetchPrompts() {
72296
+ try {
72297
+ const res = await fetch('/api/prompts');
72298
+ if (!res.ok) { showError('Prompts API error: ' + res.status); return; }
72299
+ renderBoard(await res.json());
72300
+ } catch (e) {
72301
+ showError('Could not load prompts: ' + e.message);
72302
+ }
72303
+ }
72304
+
72305
+ function renderBoard(promptFiles) {
72306
+ const columns = { 'todo': [], 'not-ready': [], 'done': [], 'failed': [] };
72307
+
72308
+ for (const file of promptFiles) {
72309
+ for (const section of file.sections) {
72310
+ const col = columns[section.status];
72311
+ if (col) col.push({ file, section });
72312
+ }
72313
+ }
72314
+
72315
+ for (const [status, cards] of Object.entries(columns)) {
72316
+ const container = document.getElementById('cards-' + status);
72317
+ const countEl = document.getElementById('count-' + status);
72318
+ if (!container) continue;
72319
+
72320
+ countEl.textContent = cards.length;
72321
+ container.innerHTML = '';
72322
+
72323
+ if (cards.length === 0) {
72324
+ container.innerHTML = '<div class="empty-column">Empty</div>';
72325
+ continue;
72326
+ }
72327
+
72328
+ for (const { file, section } of cards) {
72329
+ const card = document.createElement('div');
72330
+ card.className = 'card card-' + section.status;
72331
+ card.innerHTML =
72332
+ '<div class="card-file">' + escapeHtml(file.fileName) + ' &bull; #' + (section.index + 1) + '</div>' +
72333
+ '<div class="card-summary">' + escapeHtml(section.summary) + '</div>' +
72334
+ (section.priority > 0
72335
+ ? '<div class="card-priority">' + '!'.repeat(section.priority) + ' priority ' + section.priority + '</div>'
72336
+ : '') +
72337
+ '<div class="card-edit-hint">Click to edit</div>';
72338
+ card.onclick = () => openModal(file, section);
72339
+ container.appendChild(card);
72340
+ }
72341
+ }
72342
+ }
72343
+
72344
+ function openModal(file, section) {
72345
+ modalState = { filePath: file.filePath, sectionIndex: section.index };
72346
+
72347
+ document.getElementById('modal-file').textContent = file.fileName;
72348
+ document.getElementById('modal-section-label').textContent = 'Section ' + (section.index + 1);
72349
+
72350
+ const badge = document.getElementById('modal-status-badge');
72351
+ badge.textContent = section.status.replace('-', '\\u2011');
72352
+ badge.className = 'modal-status status-' + section.status;
72353
+
72354
+ document.getElementById('modal-content').value = section.content;
72355
+ document.getElementById('modal-overlay').classList.remove('hidden');
72356
+ setTimeout(() => document.getElementById('modal-content').focus(), 50);
72357
+ }
72358
+
72359
+ function closeModal() {
72360
+ document.getElementById('modal-overlay').classList.add('hidden');
72361
+ modalState = null;
72362
+ }
72363
+
72364
+ async function saveModal() {
72365
+ if (!modalState) return;
72366
+
72367
+ const content = document.getElementById('modal-content').value;
72368
+ const saveBtn = document.querySelector('.btn-save');
72369
+ saveBtn.disabled = true;
72370
+ saveBtn.textContent = 'Saving\\u2026';
72371
+
72372
+ try {
72373
+ const res = await fetch('/api/prompts/update', {
72374
+ method: 'PUT',
72375
+ headers: { 'Content-Type': 'application/json' },
72376
+ body: JSON.stringify({
72377
+ filePath: modalState.filePath,
72378
+ sectionIndex: modalState.sectionIndex,
72379
+ content,
72380
+ }),
72381
+ });
72382
+ if (!res.ok) throw new Error('HTTP ' + res.status);
72383
+ closeModal();
72384
+ fetchPrompts();
72385
+ } catch (e) {
72386
+ showError('Save failed: ' + e.message);
72387
+ } finally {
72388
+ saveBtn.disabled = false;
72389
+ saveBtn.textContent = 'Save';
72390
+ }
72391
+ }
72392
+
72393
+ document.getElementById('toggle-btn').onclick = async () => {
72394
+ try {
72395
+ const endpoint = lastPauseState === 'RUNNING' ? '/api/pause' : '/api/resume';
72396
+ await fetch(endpoint, { method: 'POST' });
72397
+ await fetchStatus();
72398
+ } catch (e) {
72399
+ showError('Toggle failed: ' + e.message);
72400
+ }
72401
+ };
72402
+
72403
+ document.addEventListener('keydown', (e) => {
72404
+ if (e.key === 'Escape') { closeModal(); return; }
72405
+ if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { saveModal(); return; }
72406
+ });
72407
+
72408
+ document.getElementById('modal-overlay').addEventListener('click', (e) => {
72409
+ if (e.target === document.getElementById('modal-overlay')) closeModal();
72410
+ });
72411
+
72412
+ fetchStatus();
72413
+ fetchPrompts();
72414
+ setInterval(fetchStatus, 2000);
72415
+ setInterval(fetchPrompts, 5000);
72416
+ </script>
72417
+ </body>
72418
+ </html>`;
72419
+ // Note: [🟑] Code for CLI command [coder server](scripts/run-codex-prompts/server/coderServerHtml.ts) should never be published outside of `@promptbook/cli`
72420
+ // Note: Keep in sync with apps/coder-server/index.html
72421
+
72422
+ /**
72423
+ * Directory from which prompt files are loaded, relative to the current working directory.
72424
+ *
72425
+ * @private internal constant of `ptbk coder server`
72426
+ */
72427
+ const PROMPTS_DIRECTORY_NAME = 'prompts';
72428
+ /**
72429
+ * Starts the lightweight HTTP server that serves the coder kanban UI and REST API.
72430
+ *
72431
+ * API endpoints:
72432
+ * - `GET /` β†’ HTML kanban page
72433
+ * - `GET /api/prompts` β†’ JSON list of all prompt files and sections
72434
+ * - `GET /api/status` β†’ JSON current pause state
72435
+ * - `POST /api/pause` β†’ request pause
72436
+ * - `POST /api/resume` β†’ request resume
72437
+ * - `PUT /api/prompts/update` β†’ update prompt section content
72438
+ *
72439
+ * @private internal utility of `ptbk coder server`
72440
+ */
72441
+ function startCoderHttpServer(port) {
72442
+ const promptsDir = join(process.cwd(), PROMPTS_DIRECTORY_NAME);
72443
+ const server = createServer(async (req, res) => {
72444
+ try {
72445
+ await handleRequest(req, res, promptsDir);
72446
+ }
72447
+ catch (error) {
72448
+ const message = error instanceof Error ? error.message : String(error);
72449
+ console.error(colors.red(`Coder server request error: ${message}`));
72450
+ if (!res.headersSent) {
72451
+ res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
72452
+ }
72453
+ res.end('Internal server error');
72454
+ }
72455
+ });
72456
+ server.listen(port, () => {
72457
+ console.info(spaceTrim$1(`
72458
+ Coder server running at ${colors.cyan(`http://localhost:${port}`)}
72459
+ Open the URL above in your browser to see the kanban board.
72460
+ Press ${colors.bold('p')} to pause / resume the agent runner.
72461
+ `));
72462
+ });
72463
+ return {
72464
+ close: () => {
72465
+ server.close();
72466
+ },
72467
+ };
72468
+ }
72469
+ /**
72470
+ * Routes one HTTP request to the appropriate handler.
72471
+ */
72472
+ async function handleRequest(req, res, promptsDir) {
72473
+ const urlPath = new URL(req.url || '/', `http://localhost`).pathname;
72474
+ const method = (req.method || 'GET').toUpperCase();
72475
+ // Serve the kanban UI
72476
+ if (urlPath === '/' && method === 'GET') {
72477
+ res.writeHead(200, {
72478
+ 'Content-Type': 'text/html; charset=utf-8',
72479
+ 'Cache-Control': 'no-cache',
72480
+ });
72481
+ res.end(CODER_SERVER_HTML);
72482
+ return;
72483
+ }
72484
+ // GET /api/status
72485
+ if (urlPath === '/api/status' && method === 'GET') {
72486
+ res.writeHead(200, jsonHeaders());
72487
+ res.end(JSON.stringify({
72488
+ pauseState: getPauseState(),
72489
+ pauseTargetLabel: getPauseTargetLabel(),
72490
+ }));
72491
+ return;
72492
+ }
72493
+ // GET /api/prompts
72494
+ if (urlPath === '/api/prompts' && method === 'GET') {
72495
+ const promptData = await loadPromptsForApi(promptsDir);
72496
+ res.writeHead(200, jsonHeaders());
72497
+ res.end(JSON.stringify(promptData));
72498
+ return;
72499
+ }
72500
+ // POST /api/pause
72501
+ if (urlPath === '/api/pause' && method === 'POST') {
72502
+ requestPause();
72503
+ res.writeHead(200, jsonHeaders());
72504
+ res.end(JSON.stringify({ pauseState: getPauseState() }));
72505
+ return;
72506
+ }
72507
+ // POST /api/resume
72508
+ if (urlPath === '/api/resume' && method === 'POST') {
72509
+ requestResume();
72510
+ res.writeHead(200, jsonHeaders());
72511
+ res.end(JSON.stringify({ pauseState: getPauseState() }));
72512
+ return;
72513
+ }
72514
+ // PUT /api/prompts/update
72515
+ if (urlPath === '/api/prompts/update' && method === 'PUT') {
72516
+ const body = await readRequestBody(req);
72517
+ const parsed = JSON.parse(body);
72518
+ if (typeof parsed.filePath !== 'string' ||
72519
+ typeof parsed.sectionIndex !== 'number' ||
72520
+ typeof parsed.content !== 'string') {
72521
+ throw new NotAllowed(spaceTrim$1(`
72522
+ Invalid request body for \`PUT /api/prompts/update\`.
72523
+
72524
+ Expected: \`{ filePath: string, sectionIndex: number, content: string }\`
72525
+ `));
72526
+ }
72527
+ await updatePromptSection(parsed.filePath, parsed.sectionIndex, parsed.content);
72528
+ res.writeHead(200, jsonHeaders());
72529
+ res.end(JSON.stringify({ success: true }));
72530
+ return;
72531
+ }
72532
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
72533
+ res.end('Not found');
72534
+ }
72535
+ /**
72536
+ * Loads all prompt files and converts them to the API response shape.
72537
+ */
72538
+ async function loadPromptsForApi(promptsDir) {
72539
+ try {
72540
+ const promptFiles = await loadPromptFiles(promptsDir);
72541
+ return promptFiles.map((file) => ({
72542
+ filePath: file.path,
72543
+ fileName: file.name,
72544
+ sections: file.sections.map((section) => ({
72545
+ index: section.index,
72546
+ status: section.status,
72547
+ priority: section.priority,
72548
+ summary: buildPromptSummary(file, section),
72549
+ content: buildCodexPrompt(file, section),
72550
+ })),
72551
+ }));
72552
+ }
72553
+ catch (error) {
72554
+ // Prompts directory may not exist yet; return empty list
72555
+ if (error.code === 'ENOENT') {
72556
+ return [];
72557
+ }
72558
+ throw error;
72559
+ }
72560
+ }
72561
+ /**
72562
+ * Reads the full request body as a UTF-8 string.
72563
+ */
72564
+ function readRequestBody(req) {
72565
+ return new Promise((resolve, reject) => {
72566
+ const chunks = [];
72567
+ req.on('data', (chunk) => chunks.push(chunk));
72568
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8')));
72569
+ req.on('error', reject);
72570
+ });
72571
+ }
72572
+ /**
72573
+ * Returns standard JSON response headers with no-cache directives.
72574
+ */
72575
+ function jsonHeaders() {
72576
+ return {
72577
+ 'Content-Type': 'application/json; charset=utf-8',
72578
+ 'Cache-Control': 'no-cache',
72579
+ };
72580
+ }
72581
+ // Note: [🟑] Code for CLI command [coder server](scripts/run-codex-prompts/server/runCoderHttpServer.ts) should never be published outside of `@promptbook/cli`
72582
+
72583
+ /**
72584
+ * Starts the coder server: runs prompt processing in keepAlive mode while serving a
72585
+ * kanban web UI and REST API on the given port.
72586
+ *
72587
+ * Differences from `runCodexPrompts`:
72588
+ * - Does not exit when no runnable prompts are available; instead it polls every few seconds
72589
+ * and resumes processing as soon as a new prompt becomes ready.
72590
+ * - Starts a lightweight HTTP server that serves a kanban board at `http://localhost:<port>`
72591
+ * and exposes REST endpoints for reading prompts, controlling pause state, and editing
72592
+ * prompt files directly from the browser.
72593
+ *
72594
+ * @private internal function of `ptbk coder server`
72595
+ */
72596
+ async function runCodexPromptsServer(options) {
72597
+ const { port, ...runOptions } = options;
72598
+ const serverHandle = startCoderHttpServer(port);
72599
+ console.info(colors.gray('Starting prompt runner in server (keep-alive) mode…'));
72600
+ try {
72601
+ await runCodexPrompts({
72602
+ ...runOptions,
72603
+ keepAlive: true,
72604
+ });
72605
+ }
72606
+ finally {
72607
+ serverHandle.close();
72608
+ }
72609
+ }
72610
+ // Note: [🟑] Code for CLI command [coder server](scripts/run-codex-prompts/main/runCodexPromptsServer.ts) should never be published outside of `@promptbook/cli`
72611
+
72612
+ var runCodexPromptsServer$1 = /*#__PURE__*/Object.freeze({
72613
+ __proto__: null,
72614
+ runCodexPromptsServer: runCodexPromptsServer
72615
+ });
72616
+
71541
72617
  /**
71542
72618
  * Path to the directory that holds the prompt markdown files.
71543
72619
  */