@adhdev/daemon-core 0.9.82-rc.369 → 0.9.82-rc.370

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.mjs CHANGED
@@ -311,10 +311,10 @@ function readInjected(value) {
311
311
  }
312
312
  function getDaemonBuildInfo() {
313
313
  if (cached) return cached;
314
- const commit = readInjected(true ? "4464cd9f1effac841aa1fbef3b1691d2f06d64e4" : void 0) ?? "unknown";
315
- const commitShort = readInjected(true ? "4464cd9f" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
316
- const version = readInjected(true ? "0.9.82-rc.369" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
317
- const builtAt = readInjected(true ? "2026-06-24T08:22:14.501Z" : void 0);
314
+ const commit = readInjected(true ? "84d52e533859a9dd3c3bc8bc11a2541911f7bd0c" : void 0) ?? "unknown";
315
+ const commitShort = readInjected(true ? "84d52e53" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
316
+ const version = readInjected(true ? "0.9.82-rc.370" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
317
+ const builtAt = readInjected(true ? "2026-06-24T10:07:48.772Z" : void 0);
318
318
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
319
319
  return cached;
320
320
  }
@@ -13705,54 +13705,8 @@ function isMeshCoordinatorEvent(eventName) {
13705
13705
  function shouldForceInjectMeshEvent(eventName) {
13706
13706
  return typeof eventName === "string" && MESH_FORCE_INJECT_EVENTS.has(eventName);
13707
13707
  }
13708
- function injectMeshSystemMessage(components, args) {
13709
- const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
13710
- const eventNodeId = readNonEmptyString2(args.nodeId) || readNonEmptyString2(args.metadataEvent.meshNodeId);
13711
- const traceCtx = {
13712
- taskId: args.metadataEvent.taskId,
13713
- sessionId: eventSessionId,
13714
- nodeId: eventNodeId,
13715
- meshId: args.meshId,
13716
- event: args.event
13717
- };
13718
- const sourceSession = args.sourceInstanceId ? components.instanceManager.getInstance(args.sourceInstanceId) : void 0;
13719
- const workerCoordinatorDaemonId = readNonEmptyString2(
13720
- sourceSession?.getState()?.settings?.meshCoordinatorDaemonId
13721
- );
13722
- const workerCoordinatorSessionId = readNonEmptyString2(
13723
- sourceSession?.getState()?.settings?.meshCoordinatorSessionId
13724
- ) || readNonEmptyString2(args.metadataEvent.meshCoordinatorSessionId);
13725
- const enrichedMetadataEvent = (() => {
13726
- const last = sourceSession ? getLastDisplayMessage(sourceSession.getState()) : null;
13727
- if (!last || !last.preview) return args.metadataEvent;
13728
- return {
13729
- ...args.metadataEvent,
13730
- lastMessagePreview: last.preview,
13731
- lastMessageRole: last.role,
13732
- ...last.receivedAt > 0 ? { lastMessageAt: last.receivedAt } : {}
13733
- };
13734
- })();
13735
- if (components.onMeshCoordinatorEventForwarded) {
13736
- try {
13737
- const surfacedPreview = resolveMeshSurfacedSessionPreview(enrichedMetadataEvent);
13738
- components.onMeshCoordinatorEventForwarded({
13739
- event: args.event,
13740
- meshId: args.meshId,
13741
- nodeId: eventNodeId || void 0,
13742
- ...enrichedMetadataEvent,
13743
- // Ensure a `workspace` field reaches updateMeshOwnedSession even when the
13744
- // worker provider event only carried `workspaceName`. The merge spread of
13745
- // metadataEvent above wins when it already has a non-empty `workspace`.
13746
- workspace: readNonEmptyString2(args.metadataEvent.workspace) || readNonEmptyString2(args.metadataEvent.workspaceName) || void 0,
13747
- ...surfacedPreview ? {
13748
- meshSessionLastMessagePreview: surfacedPreview.preview,
13749
- meshSessionLastMessageRole: surfacedPreview.role,
13750
- meshSessionLastMessageAt: surfacedPreview.receivedAt || void 0
13751
- } : {}
13752
- });
13753
- } catch {
13754
- }
13755
- }
13708
+ function evaluateMeshEventSuppression(args, ctx) {
13709
+ const { traceCtx, eventSessionId, eventNodeId, eventTimestamp, workerCoordinatorDaemonId } = ctx;
13756
13710
  const intentionalCleanupStop = shouldSuppressIntentionalCleanupStop({
13757
13711
  event: args.event,
13758
13712
  meshId: args.meshId,
@@ -13769,7 +13723,7 @@ function injectMeshSystemMessage(components, args) {
13769
13723
  }
13770
13724
  LOG.info("MeshEvents", `Suppressed ${args.event} for intentionally cleanup-stopped session ${eventSessionId || "(unknown session)"}`);
13771
13725
  traceMeshEventDrop("intentional_cleanup_stop", traceCtx);
13772
- return { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true };
13726
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true } };
13773
13727
  }
13774
13728
  if (args.event === "monitor:no_progress") {
13775
13729
  const reconciledCompletion = buildNoProgressCompletionReconciliation({
@@ -13781,30 +13735,28 @@ function injectMeshSystemMessage(components, args) {
13781
13735
  });
13782
13736
  if (reconciledCompletion?.source === "no_progress_reconciliation") {
13783
13737
  LOG.info("MeshEvents", `Reconciled no-progress monitor to completion for session ${eventSessionId || "(unknown session)"}`);
13784
- return injectMeshSystemMessage(components, {
13785
- ...args,
13786
- event: "agent:generating_completed",
13787
- metadataEvent: reconciledCompletion
13788
- });
13738
+ return { kind: "reconcile", metadataEvent: reconciledCompletion };
13789
13739
  }
13790
13740
  if (reconciledCompletion?.source === "no_progress_terminal_ledger_suppression") {
13791
13741
  LOG.info("MeshEvents", `Suppressed no-progress monitor because terminal ledger evidence already exists for session ${eventSessionId || "(unknown session)"}`);
13792
13742
  traceMeshEventDrop("no_progress_terminal_ledger_suppression", traceCtx, `terminalKind=${reconciledCompletion.terminalLedgerKind}`);
13793
13743
  return {
13794
- success: true,
13795
- forwarded: 0,
13796
- suppressed: true,
13797
- terminalLedgerEvidence: true,
13798
- terminalLedgerKind: reconciledCompletion.terminalLedgerKind
13744
+ kind: "suppress",
13745
+ result: {
13746
+ success: true,
13747
+ forwarded: 0,
13748
+ suppressed: true,
13749
+ terminalLedgerEvidence: true,
13750
+ terminalLedgerKind: reconciledCompletion.terminalLedgerKind
13751
+ }
13799
13752
  };
13800
13753
  }
13801
13754
  }
13802
13755
  if (isDuplicateRefineTerminalEvent(args.meshId, args.event, args.metadataEvent)) {
13803
13756
  LOG.info("MeshEvents", `Suppressed duplicate ${args.event} for refine job ${readRefineJobId({ metadataEvent: args.metadataEvent })}`);
13804
13757
  traceMeshEventDrop("duplicate_refine_terminal", traceCtx);
13805
- return { success: true, forwarded: 0, suppressed: true, duplicateRefineTerminalEvent: true };
13758
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, duplicateRefineTerminalEvent: true } };
13806
13759
  }
13807
- const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
13808
13760
  if (args.event === "agent:waiting_approval" && eventSessionId) {
13809
13761
  const duplicateApproval = isDuplicateMeshApprovalEvent({
13810
13762
  meshId: args.meshId,
@@ -13817,7 +13769,7 @@ function injectMeshSystemMessage(components, args) {
13817
13769
  if (duplicateApproval) {
13818
13770
  LOG.info("MeshEvents", `Suppressed duplicate approval event for mesh ${args.meshId} session ${eventSessionId}`);
13819
13771
  traceMeshEventDrop("duplicate_approval", traceCtx);
13820
- return { success: true, forwarded: 0, suppressed: true, duplicateApproval: true };
13772
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, duplicateApproval: true } };
13821
13773
  }
13822
13774
  }
13823
13775
  if (args.event === "agent:generating_completed" && eventSessionId) {
@@ -13840,7 +13792,7 @@ function injectMeshSystemMessage(components, args) {
13840
13792
  if (terminalProviderSessionId && terminalProviderSessionId === eventProviderSessionId || terminalFinalSummary && terminalFinalSummary === eventFinalSummary || args.metadataEvent.source === "no_progress_reconciliation") {
13841
13793
  LOG.info("MeshEvents", `Suppressed duplicate completion with existing terminal ledger evidence for mesh ${args.meshId} session ${eventSessionId}`);
13842
13794
  traceMeshEventDrop("duplicate_completion_terminal_ledger", traceCtx);
13843
- return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true, terminalLedgerEvidence: true };
13795
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true, terminalLedgerEvidence: true } };
13844
13796
  }
13845
13797
  }
13846
13798
  }
@@ -13859,7 +13811,7 @@ function injectMeshSystemMessage(components, args) {
13859
13811
  if (duplicateCompletion) {
13860
13812
  LOG.info("MeshEvents", `Suppressed duplicate completion for mesh ${args.meshId} session ${eventSessionId}`);
13861
13813
  traceMeshEventDrop("duplicate_completion", traceCtx);
13862
- return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true };
13814
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true } };
13863
13815
  }
13864
13816
  }
13865
13817
  if (args.event === "agent:stopped" && eventSessionId) {
@@ -13878,8 +13830,76 @@ function injectMeshSystemMessage(components, args) {
13878
13830
  if (duplicateStopped) {
13879
13831
  LOG.info("MeshEvents", `Suppressed duplicate stopped event for mesh ${args.meshId} session ${eventSessionId}`);
13880
13832
  traceMeshEventDrop("duplicate_stopped", traceCtx);
13881
- return { success: true, forwarded: 0, suppressed: true, duplicateStopped: true };
13833
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, duplicateStopped: true } };
13834
+ }
13835
+ }
13836
+ return null;
13837
+ }
13838
+ function injectMeshSystemMessage(components, args) {
13839
+ const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
13840
+ const eventNodeId = readNonEmptyString2(args.nodeId) || readNonEmptyString2(args.metadataEvent.meshNodeId);
13841
+ const traceCtx = {
13842
+ taskId: args.metadataEvent.taskId,
13843
+ sessionId: eventSessionId,
13844
+ nodeId: eventNodeId,
13845
+ meshId: args.meshId,
13846
+ event: args.event
13847
+ };
13848
+ const sourceSession = args.sourceInstanceId ? components.instanceManager.getInstance(args.sourceInstanceId) : void 0;
13849
+ const workerCoordinatorDaemonId = readNonEmptyString2(
13850
+ sourceSession?.getState()?.settings?.meshCoordinatorDaemonId
13851
+ );
13852
+ const workerCoordinatorSessionId = readNonEmptyString2(
13853
+ sourceSession?.getState()?.settings?.meshCoordinatorSessionId
13854
+ ) || readNonEmptyString2(args.metadataEvent.meshCoordinatorSessionId);
13855
+ const enrichedMetadataEvent = (() => {
13856
+ const last = sourceSession ? getLastDisplayMessage(sourceSession.getState()) : null;
13857
+ if (!last || !last.preview) return args.metadataEvent;
13858
+ return {
13859
+ ...args.metadataEvent,
13860
+ lastMessagePreview: last.preview,
13861
+ lastMessageRole: last.role,
13862
+ ...last.receivedAt > 0 ? { lastMessageAt: last.receivedAt } : {}
13863
+ };
13864
+ })();
13865
+ if (components.onMeshCoordinatorEventForwarded) {
13866
+ try {
13867
+ const surfacedPreview = resolveMeshSurfacedSessionPreview(enrichedMetadataEvent);
13868
+ components.onMeshCoordinatorEventForwarded({
13869
+ event: args.event,
13870
+ meshId: args.meshId,
13871
+ nodeId: eventNodeId || void 0,
13872
+ ...enrichedMetadataEvent,
13873
+ // Ensure a `workspace` field reaches updateMeshOwnedSession even when the
13874
+ // worker provider event only carried `workspaceName`. The merge spread of
13875
+ // metadataEvent above wins when it already has a non-empty `workspace`.
13876
+ workspace: readNonEmptyString2(args.metadataEvent.workspace) || readNonEmptyString2(args.metadataEvent.workspaceName) || void 0,
13877
+ ...surfacedPreview ? {
13878
+ meshSessionLastMessagePreview: surfacedPreview.preview,
13879
+ meshSessionLastMessageRole: surfacedPreview.role,
13880
+ meshSessionLastMessageAt: surfacedPreview.receivedAt || void 0
13881
+ } : {}
13882
+ });
13883
+ } catch {
13884
+ }
13885
+ }
13886
+ const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
13887
+ const suppression = evaluateMeshEventSuppression(args, {
13888
+ traceCtx,
13889
+ eventSessionId,
13890
+ eventNodeId,
13891
+ eventTimestamp,
13892
+ workerCoordinatorDaemonId
13893
+ });
13894
+ if (suppression) {
13895
+ if (suppression.kind === "reconcile") {
13896
+ return injectMeshSystemMessage(components, {
13897
+ ...args,
13898
+ event: "agent:generating_completed",
13899
+ metadataEvent: suppression.metadataEvent
13900
+ });
13882
13901
  }
13902
+ return suppression.result;
13883
13903
  }
13884
13904
  function markSessionTerminal(sessionId, outcome, occurredAtMs, opts) {
13885
13905
  const eventTaskId = readNonEmptyString2(args.metadataEvent.taskId) || void 0;
@@ -21872,6 +21892,7 @@ function getSavedProviderSessions(state, filters) {
21872
21892
  // src/index.ts
21873
21893
  init_mesh_config();
21874
21894
  init_dist();
21895
+ init_dist();
21875
21896
  init_coordinator_prompt();
21876
21897
  init_mesh_missions();
21877
21898
  init_mesh_task_stats();
@@ -27502,6 +27523,9 @@ function resolveLegacyProviderScript(fn, scriptName, params) {
27502
27523
  return fn() || null;
27503
27524
  }
27504
27525
 
27526
+ // src/commands/handler.ts
27527
+ init_hash();
27528
+
27505
27529
  // src/providers/manual-attendance.ts
27506
27530
  var AUTO_APPROVE_MANUAL_ATTENDANCE_SUPPRESS_MS = 6e4;
27507
27531
  var ManualAttendanceTracker = class {
@@ -32236,7 +32260,6 @@ var DaemonCommandHandler = class {
32236
32260
  const https = __require("https");
32237
32261
  const fs35 = __require("fs");
32238
32262
  const path42 = __require("path");
32239
- const crypto6 = __require("crypto");
32240
32263
  const REGISTRY = "https://api.adhf.dev/api/v1/registry";
32241
32264
  function fetchText(url, timeoutMs) {
32242
32265
  return new Promise((resolve24, reject) => {
@@ -32268,7 +32291,7 @@ var DaemonCommandHandler = class {
32268
32291
  `${REGISTRY}/providers/${encodeURIComponent(type)}/${encodeURIComponent(version)}/download`,
32269
32292
  3e4
32270
32293
  );
32271
- const actualChecksum = crypto6.createHash("sha256").update(manifestBody, "utf-8").digest("hex");
32294
+ const actualChecksum = sha256Hex(manifestBody);
32272
32295
  if (actualChecksum !== meta.checksum) {
32273
32296
  return { success: false, error: `checksum mismatch: expected ${meta.checksum}, got ${actualChecksum}` };
32274
32297
  }
@@ -34617,6 +34640,7 @@ import * as path25 from "path";
34617
34640
  import * as crypto4 from "crypto";
34618
34641
  import * as fs19 from "fs";
34619
34642
  import { createRequire as createRequire2 } from "module";
34643
+ init_hash();
34620
34644
 
34621
34645
  // src/providers/spec/route.ts
34622
34646
  init_provider_cli_adapter();
@@ -38303,7 +38327,7 @@ var CliProviderInstance = class _CliProviderInstance {
38303
38327
  if (!content) return;
38304
38328
  const receivedAt = Date.now();
38305
38329
  this.lastAcknowledgedUserInputAt = receivedAt;
38306
- const dedupKey = `user_input_ack:${crypto4.createHash("sha256").update(`${this.instanceId}:${content}:${receivedAt}`).digest("hex").slice(0, 24)}`;
38330
+ const dedupKey = `user_input_ack:${shortHash(`${this.instanceId}:${content}:${receivedAt}`, 24)}`;
38307
38331
  this.appendRuntimeMessage(buildChatMessage({
38308
38332
  role: "user",
38309
38333
  senderName: "User",
@@ -42173,6 +42197,7 @@ import * as fs25 from "fs";
42173
42197
  import * as path34 from "path";
42174
42198
  import * as os25 from "os";
42175
42199
  import * as chokidar from "chokidar";
42200
+ init_hash();
42176
42201
  init_logger();
42177
42202
 
42178
42203
  // src/providers/provider-schema.ts
@@ -44830,10 +44855,7 @@ var ProviderLoader = class _ProviderLoader {
44830
44855
  reject(new Error(`download timeout for ${type}`));
44831
44856
  });
44832
44857
  });
44833
- const actualChecksum = await new Promise((resolve24) => {
44834
- const crypto6 = __require("crypto");
44835
- resolve24(crypto6.createHash("sha256").update(manifestBody, "utf-8").digest("hex"));
44836
- });
44858
+ const actualChecksum = sha256Hex(manifestBody);
44837
44859
  if (actualChecksum !== checksum) {
44838
44860
  this.log(`\u26A0 Registry checksum mismatch for ${type}@${version} \u2014 skipping`);
44839
44861
  continue;
@@ -59840,477 +59862,6 @@ var DevServer = class _DevServer {
59840
59862
  async handleAutoImplement(type, req, res) {
59841
59863
  return handleAutoImplement(this, type, req, res);
59842
59864
  }
59843
- buildAutoImplPrompt(type, provider, providerDir, functions, domContext, referenceScripts, userComment, referenceType) {
59844
- if (provider.category === "cli") {
59845
- return this.buildCliAutoImplPrompt(type, provider, providerDir, functions, referenceScripts, userComment, referenceType);
59846
- }
59847
- const lines = [];
59848
- lines.push("You are implementing browser automation scripts for an IDE provider.");
59849
- lines.push("Be concise. Do NOT explain your reasoning. Just edit files directly.");
59850
- lines.push("");
59851
- lines.push(`# Target: ${provider.name || type} (${type})`);
59852
- lines.push(`Provider directory: \`${providerDir}\``);
59853
- lines.push("");
59854
- const funcToFile = {
59855
- readChat: "read_chat.js",
59856
- sendMessage: "send_message.js",
59857
- resolveAction: "resolve_action.js",
59858
- listSessions: "list_sessions.js",
59859
- listChats: "list_chats.js",
59860
- switchSession: "switch_session.js",
59861
- newSession: "new_session.js",
59862
- focusEditor: "focus_editor.js",
59863
- openPanel: "open_panel.js",
59864
- listModels: "list_models.js",
59865
- listModes: "list_modes.js",
59866
- setModel: "set_model.js",
59867
- setMode: "set_mode.js"
59868
- };
59869
- const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
59870
- const scriptsDir = path41.join(providerDir, "scripts");
59871
- const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
59872
- if (latestScriptsDir) {
59873
- lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
59874
- lines.push("");
59875
- lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
59876
- lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
59877
- lines.push("");
59878
- for (const file of fs34.readdirSync(latestScriptsDir)) {
59879
- if (file.endsWith(".js") && targetFileNames.has(file)) {
59880
- try {
59881
- const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
59882
- lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
59883
- lines.push("```javascript");
59884
- lines.push(content);
59885
- lines.push("```");
59886
- lines.push("");
59887
- } catch {
59888
- }
59889
- }
59890
- }
59891
- const refFiles = fs34.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
59892
- if (refFiles.length > 0) {
59893
- lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
59894
- lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
59895
- lines.push("");
59896
- for (const file of refFiles) {
59897
- try {
59898
- const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
59899
- lines.push(`### \`${file}\` \u{1F512}`);
59900
- lines.push("```javascript");
59901
- lines.push(content);
59902
- lines.push("```");
59903
- lines.push("");
59904
- } catch {
59905
- }
59906
- }
59907
- }
59908
- }
59909
- if (domContext) {
59910
- lines.push("## Live DOM Analysis (from CDP)");
59911
- lines.push("Use these selectors in your implementations:");
59912
- lines.push("```json");
59913
- lines.push(JSON.stringify(domContext, null, 2));
59914
- lines.push("```");
59915
- lines.push("");
59916
- }
59917
- if (Object.keys(referenceScripts).length > 0) {
59918
- lines.push(`## Reference Implementation (from ${referenceType || "antigravity"} provider)`);
59919
- lines.push("These are WORKING scripts from another IDE. Adapt the PATTERNS (not selectors) for the target IDE.");
59920
- lines.push("");
59921
- for (const fn of functions) {
59922
- const fileName = funcToFile[fn];
59923
- if (fileName && referenceScripts[fileName]) {
59924
- lines.push(`### ${fn} \u2192 \`${fileName}\``);
59925
- lines.push("```javascript");
59926
- lines.push(referenceScripts[fileName]);
59927
- lines.push("```");
59928
- lines.push("");
59929
- }
59930
- }
59931
- if (referenceScripts["scripts.js"]) {
59932
- lines.push("### Router \u2192 `scripts.js`");
59933
- lines.push("```javascript");
59934
- lines.push(referenceScripts["scripts.js"]);
59935
- lines.push("```");
59936
- lines.push("");
59937
- }
59938
- }
59939
- const docsDir = path41.join(providerDir, "../../docs");
59940
- const loadGuide = (name) => {
59941
- try {
59942
- const p = path41.join(docsDir, name);
59943
- if (fs34.existsSync(p)) return fs34.readFileSync(p, "utf-8");
59944
- } catch {
59945
- }
59946
- return null;
59947
- };
59948
- const providerGuide = loadGuide("PROVIDER_GUIDE.md");
59949
- if (providerGuide) {
59950
- lines.push("## Documentation: PROVIDER_GUIDE.md");
59951
- lines.push("```markdown");
59952
- lines.push(providerGuide);
59953
- lines.push("```");
59954
- lines.push("");
59955
- }
59956
- const cdpGuide = loadGuide("CDP_SELECTOR_GUIDE.md");
59957
- if (cdpGuide) {
59958
- lines.push("## Documentation: CDP_SELECTOR_GUIDE.md");
59959
- lines.push("```markdown");
59960
- lines.push(cdpGuide);
59961
- lines.push("```");
59962
- lines.push("");
59963
- }
59964
- lines.push("## Task");
59965
- lines.push(`Edit files in \`${providerDir}\` to implement: **${functions.join(", ")}**`);
59966
- lines.push("");
59967
- lines.push("## Rules");
59968
- lines.push('0. **\u{1F6AB} SCOPE CONSTRAINT**: You may ONLY edit files marked \u270F\uFE0F EDIT above. ALL other files are READ-ONLY. Do NOT modify, rewrite, refactor, or "improve" any file not explicitly marked as editable \u2014 even if you notice bugs or improvements. No exceptions.');
59969
- lines.push("1. **Scripts WITHOUT params** \u2192 IIFE: `(() => { ... })()`");
59970
- lines.push("2. **Scripts WITH params** \u2192 arrow: `(params) => { ... }` \u2014 router calls `(${script})(${JSON.stringify(params)})`");
59971
- lines.push("3. If live DOM analysis is included above, use it. Otherwise, discover selectors yourself via CDP before coding.");
59972
- lines.push("4. Always wrap in try-catch, return `JSON.stringify(result)`");
59973
- lines.push("5. Do NOT modify `scripts.js` router \u2014 only edit individual `*.js` files");
59974
- lines.push("6. All scripts run in the browser (CDP evaluate) \u2014 use DOM APIs only");
59975
- lines.push('7. **Cross-Platform Compatibility**: If you use ARIA labels that contain keyboard shortcuts (e.g., `Cascade (\u2318L)`), you MUST use substring matches (`aria-label*="Cascade"`) or handle both macOS (`\u2318`, `Cmd`) and Windows (`Ctrl`) so the script does not break on other operating systems.');
59976
- lines.push("8. **CRITICAL: DO NOT explore the filesystem or read other providers.** The reference implementation pattern is already provided below. Do not run `find`, `rg`, or `cat` on upstream providers. Doing so wastes context tokens and will crash the agent session. Focus entirely on modifying the target files.");
59977
- lines.push("9. Do NOT delete any files. Implement the logic by replacing the empty stubs.");
59978
- lines.push("");
59979
- lines.push("## Required Return Format");
59980
- lines.push("| Function | Return JSON |");
59981
- lines.push("|---|---|");
59982
- lines.push("| readChat | `{ id, status, title, messages: [{role, content, index, kind?, meta?}], inputContent, activeModal, controlValues?, summaryMetadata? }` \u2014 optional `kind`: standard, thought, tool, terminal; prefer explicit `controlValues` for current selections and `summaryMetadata` for compact always-visible UI metadata |");
59983
- lines.push("| sendMessage | `{ sent: false, needsTypeAndSend: true, selector }` |");
59984
- lines.push("| resolveAction | `{ resolved: true/false, clicked? }` |");
59985
- lines.push("| listSessions | `{ sessions: [{ id, title, active, index }] }` |");
59986
- lines.push("| switchSession | `{ switched: true/false }` |");
59987
- lines.push("| newSession | `{ created: true/false }` |");
59988
- lines.push("| listModels | `{ models: [{ name, id }], current }` |");
59989
- lines.push("| setModel | `{ success: true/false }` |");
59990
- lines.push("| listModes | `{ modes: [{ name, id }], current }` |");
59991
- lines.push("| setMode | `{ success: true/false }` |");
59992
- lines.push("| focusEditor | `{ focused: true/false, error? }` |");
59993
- lines.push("| openPanel | `{ opened: true/false, visible: true/false, focused?: true, error? }` |");
59994
- lines.push("");
59995
- lines.push("## \u{1F534} CRITICAL: readChat `status` Lifecycle");
59996
- lines.push("The `status` field in readChat controls how the dashboard and daemon auto-approve-loop behave.");
59997
- lines.push("Getting this wrong will break the entire automation pipeline. The status MUST reflect the ACTUAL current state:");
59998
- lines.push("");
59999
- lines.push("| Status | When to use | How to detect |");
60000
- lines.push("|---|---|---|");
60001
- lines.push("| `idle` | AI is NOT generating, no approval needed | Default state. No stop button, no spinners, no approval pills/buttons |");
60002
- lines.push('| `generating` | AI is actively streaming/thinking | ANY of: (1) Submit button icon SVG changes (e.g. arrow\u2192stop square, fill="none"\u2192fill="currentColor"), (2) Stop/Cancel button visible, (3) CSS animation, (4) Structural markers (aria-labels that only appear during generation) |');
60003
- lines.push("| `waiting_approval` | AI stopped and needs user action | Actionable buttons like Run/Skip/Accept/Reject are visible AND clickable |");
60004
- lines.push("");
60005
- lines.push("### \u26A0\uFE0F Status Detection Gotchas (MUST READ!)");
60006
- lines.push(`1. **DO NOT rely on button text/labels in the user's language.** OS locale may be Korean, Japanese, etc. Button text like "Cancel" or "Stop" will be localized. Instead, detect STRUCTURAL indicators: SVG icon changes, CSS classes, aria-labels from the extension's own React/Radix UI (which stay in English regardless of OS locale).`);
60007
- lines.push('2. **Use sendMessage to CREATE a generating state, then CAPTURE the DOM.** Send a LONG prompt (e.g. "Write an extremely detailed 5000-word essay...") so the AI takes 10+ seconds. Then periodically capture the DOM during generation to find which elements appear/change. Compare idle vs generating DOM snapshots to find reliable structural markers.');
60008
- lines.push("3. **Look for SVG icon changes in the submit button.** Many IDEs change the submit button icon from an arrow (send) to a square (stop) during generation. Check the SVG `fill` attribute or path data.");
60009
- lines.push('4. **FALSE POSITIVES from old messages**: Chat history may contain text like "Command Awaiting Approval" from PAST turns. ONLY match small leaf elements (under 80 chars) or use explicit button/pill selectors.');
60010
- lines.push("5. **Awaiting Approval pill without actions**: Some IDEs show a floating pill/banner that is just a scroll-to indicator. If NO actionable buttons exist, the status should be `idle`, NOT `waiting_approval`.");
60011
- lines.push("6. **activeModal must include actions**: When `status` is `waiting_approval`, the `activeModal` object MUST include a non-empty `actions` array.");
60012
- lines.push("");
60013
- lines.push("## Action");
60014
- lines.push("1. Edit the script files to implement working code");
60015
- lines.push("2. After editing, TEST each function using the DevConsole API (see below)");
60016
- lines.push("3. If a test fails, fix the implementation and re-test");
60017
- lines.push("4. **IMPORTANT VERIFICATION LOGIC**: When verifying your implementation, beware of state contamination! You MUST perform strict Integration Testing:");
60018
- lines.push(" - `openPanel`: Toggle buttons are usually located in the top header, sidebar, or activity bar. Prefer finding and clicking these native UI buttons over extreme CSS injection hacks if possible.");
60019
- lines.push(" - `listSessions`: If sessions are unmounted when the panel is closed, try to explicitly interact with the UI to open the history/sessions view (e.g., clicking a history icon usually found near the chat header) BEFORE scraping.");
60020
- lines.push(" - `switchSession`: Prove your switch was successful by subsequently calling `readChat` and explicitly checking that the chat context has actually changed.");
60021
- lines.push("");
60022
- lines.push("## DOM Exploration");
60023
- if (domContext) {
60024
- lines.push("A lightweight DOM snapshot is included above, but you MUST still verify selectors yourself before finalizing the scripts.");
60025
- } else {
60026
- lines.push("No DOM snapshot is included here. You MUST use your command-line tools to discover the IDE structure dynamically.");
60027
- }
60028
- lines.push("");
60029
- lines.push("### 1. Evaluate JS to explore IDE DOM");
60030
- lines.push("Use cURL to run JavaScript inside the IDE:");
60031
- lines.push("```bash");
60032
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cdp/evaluate \\`);
60033
- lines.push(` -H "Content-Type: application/json" \\`);
60034
- lines.push(` -d '{"expression": "document.body.innerHTML.substring(0, 1000)", "ideType": "${type}"}'`);
60035
- lines.push("```");
60036
- lines.push("");
60037
- lines.push("### 2. Test your generated function");
60038
- lines.push("Once you save the file, test it by running:");
60039
- lines.push("```bash");
60040
- lines.push(`curl -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/providers/reload`);
60041
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/scripts/run -H "Content-Type: application/json" -d '{"script": "readChat", "type": "${type}", "ideType": "${type}"}'`);
60042
- lines.push("```");
60043
- lines.push("");
60044
- lines.push("### Task Workflow");
60045
- lines.push("1. Write bash scripts to `curl` the CDP evaluate API above to find exactly where `.chat-message`, etc., are located.");
60046
- lines.push("2. Iteratively explore until you are confident in your selectors.");
60047
- lines.push("3. Edit the `.js` files using the selectors you discovered.");
60048
- lines.push("4. Reload providers and TEST your script via the API.");
60049
- lines.push("");
60050
- lines.push("### \u{1F525} Advanced UI Parsing (CRUCIAL for `readChat`)");
60051
- lines.push("Your `readChat` must flawlessly parse complex UI elements (tables, code blocks, tool calls, and AI thoughts). The quality must match the `antigravity` reference.");
60052
- lines.push("To achieve this, you MUST generate a live test scenario:");
60053
- lines.push(`1. Early in your process, send a rich prompt to the IDE using the API:`);
60054
- lines.push(` \`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/scripts/run -H "Content-Type: application/json" -d '{"script": "sendMessage", "type": "${type}", "ideType": "${type}", "args": {"message": "Write a python script, draw a markdown table, use a tool, and show your reasoning/thought process"}}'\``);
60055
- lines.push("2. Wait a few seconds for the IDE AI to generate these elements in the UI.");
60056
- lines.push("3. Use CDP evaluate to deeply inspect the DOM structure of the newly generated tables, code blocks, thought blocks, and tool calls.");
60057
- lines.push("4. Ensure `readChat` extracts `content` with precise markdown formatting (especially for tables/code) and assigns correct `kind` tags (`thought`, `tool`, `terminal`).");
60058
- lines.push("");
60059
- lines.push("## \u{1F9EA} MANDATORY: Status Integration Test");
60060
- lines.push("Before finishing, you MUST run this end-to-end test to verify readChat status transitions work:");
60061
- lines.push("");
60062
- lines.push("### Step 1: Baseline \u2014 confirm idle");
60063
- lines.push("```bash");
60064
- lines.push(`curl -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/providers/reload`);
60065
- lines.push(`RESULT=$(curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/scripts/run -H "Content-Type: application/json" -d '{"script": "readChat", "type": "${type}", "ideType": "${type}"}')`);
60066
- lines.push(`echo "$RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); r=d.get('result',d); r=json.loads(r) if isinstance(r,str) else r; assert r.get('status')=='idle', f'Expected idle, got {r.get(chr(34)+chr(115)+chr(116)+chr(97)+chr(116)+chr(117)+chr(115)+chr(34))}'; print('Step 1 PASS: status=idle')"`);
60067
- lines.push("```");
60068
- lines.push("");
60069
- lines.push("### Step 2: Send a LONG message that triggers extended generation (10+ seconds)");
60070
- lines.push("```bash");
60071
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/scripts/run -H "Content-Type: application/json" -d '{"script": "sendMessage", "type": "${type}", "ideType": "${type}", "args": {"message": "Write an extremely detailed 5000-word essay about the history of artificial intelligence from Alan Turing to 2025. Be very thorough and verbose."}}'`);
60072
- lines.push("sleep 3");
60073
- lines.push("```");
60074
- lines.push("");
60075
- lines.push("### Step 3: Check generating OR completed");
60076
- lines.push("The AI may still be generating OR may have finished already. Either generating or idle is acceptable:");
60077
- lines.push("```bash");
60078
- lines.push(`RESULT=$(curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/scripts/run -H "Content-Type: application/json" -d '{"script": "readChat", "type": "${type}", "ideType": "${type}"}')`);
60079
- lines.push(`echo "$RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); r=d.get('result',d); r=json.loads(r) if isinstance(r,str) else r; s=r.get('status'); assert s in ('generating','idle','waiting_approval'), f'Unexpected: {s}'; print(f'Step 3 PASS: status={s}')"`);
60080
- lines.push("```");
60081
- lines.push("");
60082
- lines.push("### Step 4: Wait for completion and verify new message");
60083
- lines.push("```bash");
60084
- lines.push("sleep 10");
60085
- lines.push(`RESULT=$(curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/scripts/run -H "Content-Type: application/json" -d '{"script": "readChat", "type": "${type}", "ideType": "${type}"}')`);
60086
- lines.push(`echo "$RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); r=d.get('result',d); r=json.loads(r) if isinstance(r,str) else r; s=r.get('status'); msgs=r.get('messages',[]); assert s=='idle', f'Expected idle, got {s}'; assert len(msgs)>0, 'No messages'; print(f'Step 4 PASS: status={s}, messages={len(msgs)}')"`);
60087
- lines.push("```");
60088
- lines.push("");
60089
- lines.push("If ANY step fails, fix your implementation and re-run the test. Do NOT finish until all 4 steps pass.");
60090
- lines.push("");
60091
- if (userComment) {
60092
- lines.push("## \u26A0\uFE0F User Instructions (HIGH PRIORITY)");
60093
- lines.push("The user has provided the following additional instructions. Follow them strictly:");
60094
- lines.push("");
60095
- lines.push(userComment);
60096
- lines.push("");
60097
- }
60098
- lines.push("Start NOW. Do not ask for permission. Explore the DOM -> Code -> Test.");
60099
- return lines.join("\n");
60100
- }
60101
- buildCliAutoImplPrompt(type, provider, providerDir, functions, referenceScripts, userComment, referenceType) {
60102
- const lines = [];
60103
- lines.push("You are implementing PTY parsing scripts for a CLI provider.");
60104
- lines.push("Be concise. Do NOT explain your reasoning. Edit files directly and verify with the local DevServer.");
60105
- lines.push("");
60106
- lines.push(`# Target: ${provider.name || type} (${type})`);
60107
- lines.push(`Provider directory: \`${providerDir}\``);
60108
- lines.push("Provider category: `cli`");
60109
- lines.push("");
60110
- const funcToFile = {
60111
- parseSession: "parse_session.js",
60112
- detectStatus: "detect_status.js",
60113
- parseApproval: "parse_approval.js"
60114
- };
60115
- const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
60116
- const scriptsDir = path41.join(providerDir, "scripts");
60117
- const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
60118
- if (latestScriptsDir) {
60119
- lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
60120
- lines.push("");
60121
- lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
60122
- lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
60123
- lines.push("");
60124
- for (const file of fs34.readdirSync(latestScriptsDir)) {
60125
- if (!file.endsWith(".js")) continue;
60126
- if (!targetFileNames.has(file)) continue;
60127
- try {
60128
- const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
60129
- lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
60130
- lines.push("```javascript");
60131
- lines.push(content);
60132
- lines.push("```");
60133
- lines.push("");
60134
- } catch {
60135
- }
60136
- }
60137
- const refFiles = fs34.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
60138
- if (refFiles.length > 0) {
60139
- lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
60140
- lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
60141
- lines.push("");
60142
- for (const file of refFiles) {
60143
- try {
60144
- const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
60145
- lines.push(`### \`${file}\` \u{1F512}`);
60146
- lines.push("```javascript");
60147
- lines.push(content);
60148
- lines.push("```");
60149
- lines.push("");
60150
- } catch {
60151
- }
60152
- }
60153
- }
60154
- }
60155
- if (Object.keys(referenceScripts).length > 0) {
60156
- lines.push(`## Reference Implementation (from ${referenceType || "another CLI"} provider)`);
60157
- lines.push("These are working CLI PTY parser scripts. Reuse the parsing shape and runtime contract, but adapt to the target CLI screen.");
60158
- lines.push("");
60159
- for (const fn of functions) {
60160
- const fileName = funcToFile[fn];
60161
- if (fileName && referenceScripts[fileName]) {
60162
- lines.push(`### ${fn} \u2192 \`${fileName}\``);
60163
- lines.push("```javascript");
60164
- lines.push(referenceScripts[fileName]);
60165
- lines.push("```");
60166
- lines.push("");
60167
- }
60168
- }
60169
- if (referenceScripts["scripts.js"]) {
60170
- lines.push("### Router \u2192 `scripts.js`");
60171
- lines.push("```javascript");
60172
- lines.push(referenceScripts["scripts.js"]);
60173
- lines.push("```");
60174
- lines.push("");
60175
- }
60176
- }
60177
- const docsDir = path41.join(providerDir, "../../docs");
60178
- const loadGuide = (name) => {
60179
- try {
60180
- const p = path41.join(docsDir, name);
60181
- if (fs34.existsSync(p)) return fs34.readFileSync(p, "utf-8");
60182
- } catch {
60183
- }
60184
- return null;
60185
- };
60186
- const providerGuide = loadGuide("PROVIDER_GUIDE.md");
60187
- if (providerGuide) {
60188
- lines.push("## Documentation: PROVIDER_GUIDE.md");
60189
- lines.push("```markdown");
60190
- lines.push(providerGuide);
60191
- lines.push("```");
60192
- lines.push("");
60193
- }
60194
- lines.push("## Runtime Contract");
60195
- lines.push("The daemon runtime is already implemented in `packages/daemon-core/src/cli-adapters/provider-cli-adapter.ts`.");
60196
- lines.push("Your scripts receive PTY-derived input and must return plain JS objects.");
60197
- lines.push("");
60198
- lines.push("| Function | Input | Return |");
60199
- lines.push("|---|---|---|");
60200
- lines.push("| `parseSession` | `{ buffer, rawBuffer, recentBuffer, screenText, messages, partialResponse }` | `{ id, status, title, messages, activeModal }` |");
60201
- lines.push("| `detectStatus` | `{ tail, screenText, rawBuffer }` | `idle`, `generating`, `waiting_approval`, or `error` |");
60202
- lines.push("| `parseApproval` | `{ buffer, rawBuffer, tail }` | `{ message, buttons }` or `null` |");
60203
- lines.push("");
60204
- lines.push("## Primary Source of Truth");
60205
- lines.push("The runtime now provides a reliable current-screen snapshot. Treat `screenText` as the primary source of truth for the LIVE visible UI.");
60206
- lines.push("That means:");
60207
- lines.push("- Use `screenText` first for prompt detection, approval UI, status, and visible assistant content.");
60208
- lines.push("- Use `rawBuffer` only as supporting evidence when ANSI/style/cursor cues matter.");
60209
- lines.push("- Use `buffer` only when the visible screen does not contain enough text to recover the latest assistant answer.");
60210
- lines.push("- Do NOT build the parser around stale transcript noise if the current screen already gives the answer.");
60211
- lines.push("");
60212
- lines.push("## Rules");
60213
- lines.push('0. **\u{1F6AB} SCOPE CONSTRAINT**: You may ONLY edit files marked \u270F\uFE0F EDIT above. ALL other files are READ-ONLY. Do NOT modify, rewrite, refactor, or "improve" any file not explicitly marked as editable \u2014 even if you notice bugs or improvements. No exceptions.');
60214
- lines.push("1. These scripts run in Node.js CommonJS, not in the browser. Do NOT use DOM APIs.");
60215
- lines.push("2. Prefer `screenText` for current visible UI state. It is now the PTY equivalent of a trustworthy live DOM snapshot.");
60216
- lines.push("3. Use `messages` as prior transcript state so redraws do not duplicate old turns on every parse.");
60217
- lines.push("4. Use `partialResponse` for the actively streaming assistant text when status is `generating`.");
60218
- lines.push("5. `detectStatus` must stay lightweight and current-screen-oriented. Prefer the active bottom-of-screen region over stale history.");
60219
- lines.push("6. `parseApproval` should understand the live approval area and return clean button labels from the CURRENT visible modal.");
60220
- lines.push("7. Use `rawBuffer` only when ANSI/control-sequence artifacts or style cues matter. Do not depend on raw escape noise unless necessary.");
60221
- lines.push("8. Keep exports compatible with the existing `scripts.js` router (`module.exports = function ...`).");
60222
- lines.push('9. Do NOT modify ANY file not explicitly marked \u270F\uFE0F EDIT above. No exceptions \u2014 no "tiny supporting changes" to other files.');
60223
- lines.push("10. When the verification API returns `instanceId`, keep using that exact instance for follow-up `send`, `resolve`, `raw`, and `stop` calls. Do not assume type-only routing is safe if multiple sessions exist.");
60224
- lines.push("11. Do NOT repeatedly dump the same target files. Read the target scripts once, reproduce the bug, then move directly to patching.");
60225
- lines.push("12. If the user instructions include concrete screen text, raw PTY snippets, or a specific repro, treat that as the primary acceptance criteria.");
60226
- lines.push("13. After the first successful live repro, stop broad diagnosis. Edit the scripts, reload, and verify. Do not burn tokens on repeated re-inspection without code changes.");
60227
- lines.push("14. If the visible current screen is clean and sufficient, do NOT fall back to complex buffer heuristics. Simpler current-screen parsing is preferred.");
60228
- lines.push("15. Before changing parser logic, verify whether `provider.json` submit/approval behavior (`sendDelayMs`, `approvalKeys`, submit strategy) is the simpler and more correct fix.");
60229
- lines.push("");
60230
- lines.push("## Task");
60231
- lines.push(`Edit files in \`${providerDir}\` to implement: **${functions.join(", ")}**`);
60232
- lines.push("");
60233
- lines.push("## Verification API");
60234
- lines.push("Use the DevServer CLI debug endpoints, not DOM/CDP routes.");
60235
- lines.push("");
60236
- lines.push("### 1. Launch the target CLI");
60237
- lines.push("```bash");
60238
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/launch \\`);
60239
- lines.push(' -H "Content-Type: application/json" \\');
60240
- lines.push(` -d '{"type":"${type}","workingDir":"${providerDir.replace(/\\/g, "\\\\")}"}'`);
60241
- lines.push("```");
60242
- lines.push("");
60243
- lines.push("### 2. Inspect parsed + raw adapter state");
60244
- lines.push("```bash");
60245
- lines.push(`curl -sS http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/debug/${type}`);
60246
- lines.push(`curl -sS http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/trace/${type}`);
60247
- lines.push(`curl -sS http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/status`);
60248
- lines.push("```");
60249
- lines.push("");
60250
- lines.push("The debug payload should be read in this priority order:");
60251
- lines.push("1. `screenText` / current visible state");
60252
- lines.push("2. parsed `status`, `messages`, `activeModal`");
60253
- lines.push("3. `rawBuffer` only for style/control-sequence cues");
60254
- lines.push("4. `buffer` only when the current screen is insufficient");
60255
- lines.push("");
60256
- lines.push("Extract the current `instanceId` from the launch or status response and keep using it below.");
60257
- lines.push("");
60258
- lines.push("### 3. Send a realistic approval-triggering prompt");
60259
- lines.push("```bash");
60260
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/send \\`);
60261
- lines.push(' -H "Content-Type: application/json" \\');
60262
- lines.push(` -d '{"type":"${type}","instanceId":"<INSTANCE_ID>","text":"Create a file at tmp/adhdev_provider_fix_test.py that prints the current working directory and the squares of 1 through 5, then run python3 tmp/adhdev_provider_fix_test.py and tell me the exact output."}'`);
60263
- lines.push("```");
60264
- lines.push("");
60265
- lines.push("### 4. If approval appears, resolve it until the CLI reaches idle");
60266
- lines.push("```bash");
60267
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/resolve \\`);
60268
- lines.push(' -H "Content-Type: application/json" \\');
60269
- lines.push(` -d '{"type":"${type}","instanceId":"<INSTANCE_ID>","buttonIndex":0}'`);
60270
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/raw \\`);
60271
- lines.push(' -H "Content-Type: application/json" \\');
60272
- lines.push(` -d '{"type":"${type}","instanceId":"<INSTANCE_ID>","keys":"1"}'`);
60273
- lines.push("```");
60274
- lines.push("");
60275
- lines.push("Use `resolve` when the parsed modal buttons are correct. Use `raw` when the CLI expects a literal keystroke like `1`, `y`, or Enter. Repeat until idle.");
60276
- lines.push("");
60277
- lines.push("### Patch Discipline");
60278
- lines.push("Once the repro is confirmed, immediately edit the target files. Avoid loops where you keep re-reading long files or re-running the same debug commands without changing code.");
60279
- lines.push("");
60280
- lines.push("### 5. Verify the side effects outside the CLI");
60281
- lines.push("```bash");
60282
- lines.push("test -f tmp/adhdev_provider_fix_test.py");
60283
- lines.push("python3 tmp/adhdev_provider_fix_test.py");
60284
- lines.push("```");
60285
- lines.push("");
60286
- lines.push("### 6. Stop the CLI when finished");
60287
- lines.push("```bash");
60288
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/stop \\`);
60289
- lines.push(' -H "Content-Type: application/json" \\');
60290
- lines.push(` -d '{"type":"${type}","instanceId":"<INSTANCE_ID>"}'`);
60291
- lines.push("```");
60292
- lines.push("");
60293
- lines.push("## Required Validation");
60294
- lines.push("1. Confirm `detectStatus` changes sensibly between startup, generating, approval, and idle.");
60295
- lines.push("2. Confirm `parseSession` produces a stable transcript without duplicating past turns when the PTY redraws.");
60296
- lines.push("3. Confirm the latest assistant message streams through `partialResponse` while generation is in progress.");
60297
- lines.push("4. Confirm approval parsing returns meaningful button labels when the CLI requests permission.");
60298
- lines.push("5. Confirm the Python file was actually created and executed, not just described in chat text.");
60299
- lines.push("6. Confirm the final assistant transcript includes the exact Python output, including the working directory line and the five square numbers.");
60300
- lines.push("7. Re-run the debug endpoints after edits. Do NOT finish until the parsed result looks correct.");
60301
- lines.push("8. Confirm the parser still works after a redraw or scroll change without duplicating transcript history.");
60302
- lines.push("9. Confirm the implementation prefers current-screen signals over stale history when both are present.");
60303
- lines.push("");
60304
- if (userComment) {
60305
- lines.push("## \u26A0\uFE0F User Instructions (HIGH PRIORITY)");
60306
- lines.push("The user has provided the following additional instructions. Follow them strictly:");
60307
- lines.push("");
60308
- lines.push(userComment);
60309
- lines.push("");
60310
- }
60311
- lines.push("Start NOW. Launch the CLI, inspect PTY state, edit the scripts, and verify via the CLI debug endpoints.");
60312
- return lines.join("\n");
60313
- }
60314
59865
  handleAutoImplSSE(type, req, res) {
60315
59866
  handleAutoImplSSE(this, type, req, res);
60316
59867
  }
@@ -62193,6 +61744,7 @@ export {
62193
61744
  markSetupComplete,
62194
61745
  markStaleDirectDispatches,
62195
61746
  maybeRunDaemonUpgradeHelperFromEnv,
61747
+ meshNodeIdMatches,
62196
61748
  namedKeyToAnsi,
62197
61749
  namedKeysToAnsi,
62198
61750
  nodeSatisfiesRequiredTags,
@@ -62209,6 +61761,7 @@ export {
62209
61761
  normalizeManagedStatus,
62210
61762
  normalizeMeshCapabilityTags,
62211
61763
  normalizeMeshDaemonRole,
61764
+ normalizeMeshNodeId,
62212
61765
  normalizeMeshSchedulingStrategy,
62213
61766
  normalizeMeshTaskMode,
62214
61767
  normalizeMeshWorkerResult,