@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.js CHANGED
@@ -316,10 +316,10 @@ function readInjected(value) {
316
316
  }
317
317
  function getDaemonBuildInfo() {
318
318
  if (cached) return cached;
319
- const commit = readInjected(true ? "4464cd9f1effac841aa1fbef3b1691d2f06d64e4" : void 0) ?? "unknown";
320
- const commitShort = readInjected(true ? "4464cd9f" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
321
- const version = readInjected(true ? "0.9.82-rc.369" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
322
- const builtAt = readInjected(true ? "2026-06-24T08:22:14.501Z" : void 0);
319
+ const commit = readInjected(true ? "84d52e533859a9dd3c3bc8bc11a2541911f7bd0c" : void 0) ?? "unknown";
320
+ const commitShort = readInjected(true ? "84d52e53" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
321
+ const version = readInjected(true ? "0.9.82-rc.370" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
322
+ const builtAt = readInjected(true ? "2026-06-24T10:07:48.772Z" : void 0);
323
323
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
324
324
  return cached;
325
325
  }
@@ -13709,54 +13709,8 @@ function isMeshCoordinatorEvent(eventName) {
13709
13709
  function shouldForceInjectMeshEvent(eventName) {
13710
13710
  return typeof eventName === "string" && MESH_FORCE_INJECT_EVENTS.has(eventName);
13711
13711
  }
13712
- function injectMeshSystemMessage(components, args) {
13713
- const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
13714
- const eventNodeId = readNonEmptyString2(args.nodeId) || readNonEmptyString2(args.metadataEvent.meshNodeId);
13715
- const traceCtx = {
13716
- taskId: args.metadataEvent.taskId,
13717
- sessionId: eventSessionId,
13718
- nodeId: eventNodeId,
13719
- meshId: args.meshId,
13720
- event: args.event
13721
- };
13722
- const sourceSession = args.sourceInstanceId ? components.instanceManager.getInstance(args.sourceInstanceId) : void 0;
13723
- const workerCoordinatorDaemonId = readNonEmptyString2(
13724
- sourceSession?.getState()?.settings?.meshCoordinatorDaemonId
13725
- );
13726
- const workerCoordinatorSessionId = readNonEmptyString2(
13727
- sourceSession?.getState()?.settings?.meshCoordinatorSessionId
13728
- ) || readNonEmptyString2(args.metadataEvent.meshCoordinatorSessionId);
13729
- const enrichedMetadataEvent = (() => {
13730
- const last = sourceSession ? getLastDisplayMessage(sourceSession.getState()) : null;
13731
- if (!last || !last.preview) return args.metadataEvent;
13732
- return {
13733
- ...args.metadataEvent,
13734
- lastMessagePreview: last.preview,
13735
- lastMessageRole: last.role,
13736
- ...last.receivedAt > 0 ? { lastMessageAt: last.receivedAt } : {}
13737
- };
13738
- })();
13739
- if (components.onMeshCoordinatorEventForwarded) {
13740
- try {
13741
- const surfacedPreview = resolveMeshSurfacedSessionPreview(enrichedMetadataEvent);
13742
- components.onMeshCoordinatorEventForwarded({
13743
- event: args.event,
13744
- meshId: args.meshId,
13745
- nodeId: eventNodeId || void 0,
13746
- ...enrichedMetadataEvent,
13747
- // Ensure a `workspace` field reaches updateMeshOwnedSession even when the
13748
- // worker provider event only carried `workspaceName`. The merge spread of
13749
- // metadataEvent above wins when it already has a non-empty `workspace`.
13750
- workspace: readNonEmptyString2(args.metadataEvent.workspace) || readNonEmptyString2(args.metadataEvent.workspaceName) || void 0,
13751
- ...surfacedPreview ? {
13752
- meshSessionLastMessagePreview: surfacedPreview.preview,
13753
- meshSessionLastMessageRole: surfacedPreview.role,
13754
- meshSessionLastMessageAt: surfacedPreview.receivedAt || void 0
13755
- } : {}
13756
- });
13757
- } catch {
13758
- }
13759
- }
13712
+ function evaluateMeshEventSuppression(args, ctx) {
13713
+ const { traceCtx, eventSessionId, eventNodeId, eventTimestamp, workerCoordinatorDaemonId } = ctx;
13760
13714
  const intentionalCleanupStop = shouldSuppressIntentionalCleanupStop({
13761
13715
  event: args.event,
13762
13716
  meshId: args.meshId,
@@ -13773,7 +13727,7 @@ function injectMeshSystemMessage(components, args) {
13773
13727
  }
13774
13728
  LOG.info("MeshEvents", `Suppressed ${args.event} for intentionally cleanup-stopped session ${eventSessionId || "(unknown session)"}`);
13775
13729
  traceMeshEventDrop("intentional_cleanup_stop", traceCtx);
13776
- return { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true };
13730
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true } };
13777
13731
  }
13778
13732
  if (args.event === "monitor:no_progress") {
13779
13733
  const reconciledCompletion = buildNoProgressCompletionReconciliation({
@@ -13785,30 +13739,28 @@ function injectMeshSystemMessage(components, args) {
13785
13739
  });
13786
13740
  if (reconciledCompletion?.source === "no_progress_reconciliation") {
13787
13741
  LOG.info("MeshEvents", `Reconciled no-progress monitor to completion for session ${eventSessionId || "(unknown session)"}`);
13788
- return injectMeshSystemMessage(components, {
13789
- ...args,
13790
- event: "agent:generating_completed",
13791
- metadataEvent: reconciledCompletion
13792
- });
13742
+ return { kind: "reconcile", metadataEvent: reconciledCompletion };
13793
13743
  }
13794
13744
  if (reconciledCompletion?.source === "no_progress_terminal_ledger_suppression") {
13795
13745
  LOG.info("MeshEvents", `Suppressed no-progress monitor because terminal ledger evidence already exists for session ${eventSessionId || "(unknown session)"}`);
13796
13746
  traceMeshEventDrop("no_progress_terminal_ledger_suppression", traceCtx, `terminalKind=${reconciledCompletion.terminalLedgerKind}`);
13797
13747
  return {
13798
- success: true,
13799
- forwarded: 0,
13800
- suppressed: true,
13801
- terminalLedgerEvidence: true,
13802
- terminalLedgerKind: reconciledCompletion.terminalLedgerKind
13748
+ kind: "suppress",
13749
+ result: {
13750
+ success: true,
13751
+ forwarded: 0,
13752
+ suppressed: true,
13753
+ terminalLedgerEvidence: true,
13754
+ terminalLedgerKind: reconciledCompletion.terminalLedgerKind
13755
+ }
13803
13756
  };
13804
13757
  }
13805
13758
  }
13806
13759
  if (isDuplicateRefineTerminalEvent(args.meshId, args.event, args.metadataEvent)) {
13807
13760
  LOG.info("MeshEvents", `Suppressed duplicate ${args.event} for refine job ${readRefineJobId({ metadataEvent: args.metadataEvent })}`);
13808
13761
  traceMeshEventDrop("duplicate_refine_terminal", traceCtx);
13809
- return { success: true, forwarded: 0, suppressed: true, duplicateRefineTerminalEvent: true };
13762
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, duplicateRefineTerminalEvent: true } };
13810
13763
  }
13811
- const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
13812
13764
  if (args.event === "agent:waiting_approval" && eventSessionId) {
13813
13765
  const duplicateApproval = isDuplicateMeshApprovalEvent({
13814
13766
  meshId: args.meshId,
@@ -13821,7 +13773,7 @@ function injectMeshSystemMessage(components, args) {
13821
13773
  if (duplicateApproval) {
13822
13774
  LOG.info("MeshEvents", `Suppressed duplicate approval event for mesh ${args.meshId} session ${eventSessionId}`);
13823
13775
  traceMeshEventDrop("duplicate_approval", traceCtx);
13824
- return { success: true, forwarded: 0, suppressed: true, duplicateApproval: true };
13776
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, duplicateApproval: true } };
13825
13777
  }
13826
13778
  }
13827
13779
  if (args.event === "agent:generating_completed" && eventSessionId) {
@@ -13844,7 +13796,7 @@ function injectMeshSystemMessage(components, args) {
13844
13796
  if (terminalProviderSessionId && terminalProviderSessionId === eventProviderSessionId || terminalFinalSummary && terminalFinalSummary === eventFinalSummary || args.metadataEvent.source === "no_progress_reconciliation") {
13845
13797
  LOG.info("MeshEvents", `Suppressed duplicate completion with existing terminal ledger evidence for mesh ${args.meshId} session ${eventSessionId}`);
13846
13798
  traceMeshEventDrop("duplicate_completion_terminal_ledger", traceCtx);
13847
- return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true, terminalLedgerEvidence: true };
13799
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true, terminalLedgerEvidence: true } };
13848
13800
  }
13849
13801
  }
13850
13802
  }
@@ -13863,7 +13815,7 @@ function injectMeshSystemMessage(components, args) {
13863
13815
  if (duplicateCompletion) {
13864
13816
  LOG.info("MeshEvents", `Suppressed duplicate completion for mesh ${args.meshId} session ${eventSessionId}`);
13865
13817
  traceMeshEventDrop("duplicate_completion", traceCtx);
13866
- return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true };
13818
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true } };
13867
13819
  }
13868
13820
  }
13869
13821
  if (args.event === "agent:stopped" && eventSessionId) {
@@ -13882,8 +13834,76 @@ function injectMeshSystemMessage(components, args) {
13882
13834
  if (duplicateStopped) {
13883
13835
  LOG.info("MeshEvents", `Suppressed duplicate stopped event for mesh ${args.meshId} session ${eventSessionId}`);
13884
13836
  traceMeshEventDrop("duplicate_stopped", traceCtx);
13885
- return { success: true, forwarded: 0, suppressed: true, duplicateStopped: true };
13837
+ return { kind: "suppress", result: { success: true, forwarded: 0, suppressed: true, duplicateStopped: true } };
13838
+ }
13839
+ }
13840
+ return null;
13841
+ }
13842
+ function injectMeshSystemMessage(components, args) {
13843
+ const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
13844
+ const eventNodeId = readNonEmptyString2(args.nodeId) || readNonEmptyString2(args.metadataEvent.meshNodeId);
13845
+ const traceCtx = {
13846
+ taskId: args.metadataEvent.taskId,
13847
+ sessionId: eventSessionId,
13848
+ nodeId: eventNodeId,
13849
+ meshId: args.meshId,
13850
+ event: args.event
13851
+ };
13852
+ const sourceSession = args.sourceInstanceId ? components.instanceManager.getInstance(args.sourceInstanceId) : void 0;
13853
+ const workerCoordinatorDaemonId = readNonEmptyString2(
13854
+ sourceSession?.getState()?.settings?.meshCoordinatorDaemonId
13855
+ );
13856
+ const workerCoordinatorSessionId = readNonEmptyString2(
13857
+ sourceSession?.getState()?.settings?.meshCoordinatorSessionId
13858
+ ) || readNonEmptyString2(args.metadataEvent.meshCoordinatorSessionId);
13859
+ const enrichedMetadataEvent = (() => {
13860
+ const last = sourceSession ? getLastDisplayMessage(sourceSession.getState()) : null;
13861
+ if (!last || !last.preview) return args.metadataEvent;
13862
+ return {
13863
+ ...args.metadataEvent,
13864
+ lastMessagePreview: last.preview,
13865
+ lastMessageRole: last.role,
13866
+ ...last.receivedAt > 0 ? { lastMessageAt: last.receivedAt } : {}
13867
+ };
13868
+ })();
13869
+ if (components.onMeshCoordinatorEventForwarded) {
13870
+ try {
13871
+ const surfacedPreview = resolveMeshSurfacedSessionPreview(enrichedMetadataEvent);
13872
+ components.onMeshCoordinatorEventForwarded({
13873
+ event: args.event,
13874
+ meshId: args.meshId,
13875
+ nodeId: eventNodeId || void 0,
13876
+ ...enrichedMetadataEvent,
13877
+ // Ensure a `workspace` field reaches updateMeshOwnedSession even when the
13878
+ // worker provider event only carried `workspaceName`. The merge spread of
13879
+ // metadataEvent above wins when it already has a non-empty `workspace`.
13880
+ workspace: readNonEmptyString2(args.metadataEvent.workspace) || readNonEmptyString2(args.metadataEvent.workspaceName) || void 0,
13881
+ ...surfacedPreview ? {
13882
+ meshSessionLastMessagePreview: surfacedPreview.preview,
13883
+ meshSessionLastMessageRole: surfacedPreview.role,
13884
+ meshSessionLastMessageAt: surfacedPreview.receivedAt || void 0
13885
+ } : {}
13886
+ });
13887
+ } catch {
13888
+ }
13889
+ }
13890
+ const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
13891
+ const suppression = evaluateMeshEventSuppression(args, {
13892
+ traceCtx,
13893
+ eventSessionId,
13894
+ eventNodeId,
13895
+ eventTimestamp,
13896
+ workerCoordinatorDaemonId
13897
+ });
13898
+ if (suppression) {
13899
+ if (suppression.kind === "reconcile") {
13900
+ return injectMeshSystemMessage(components, {
13901
+ ...args,
13902
+ event: "agent:generating_completed",
13903
+ metadataEvent: suppression.metadataEvent
13904
+ });
13886
13905
  }
13906
+ return suppression.result;
13887
13907
  }
13888
13908
  function markSessionTerminal(sessionId, outcome, occurredAtMs, opts) {
13889
13909
  const eventTaskId = readNonEmptyString2(args.metadataEvent.taskId) || void 0;
@@ -20886,6 +20906,7 @@ __export(index_exports, {
20886
20906
  markSetupComplete: () => markSetupComplete,
20887
20907
  markStaleDirectDispatches: () => markStaleDirectDispatches,
20888
20908
  maybeRunDaemonUpgradeHelperFromEnv: () => maybeRunDaemonUpgradeHelperFromEnv,
20909
+ meshNodeIdMatches: () => meshNodeIdMatches,
20889
20910
  namedKeyToAnsi: () => namedKeyToAnsi,
20890
20911
  namedKeysToAnsi: () => namedKeysToAnsi,
20891
20912
  nodeSatisfiesRequiredTags: () => nodeSatisfiesRequiredTags,
@@ -20902,6 +20923,7 @@ __export(index_exports, {
20902
20923
  normalizeManagedStatus: () => normalizeManagedStatus,
20903
20924
  normalizeMeshCapabilityTags: () => normalizeMeshCapabilityTags,
20904
20925
  normalizeMeshDaemonRole: () => normalizeMeshDaemonRole,
20926
+ normalizeMeshNodeId: () => normalizeMeshNodeId,
20905
20927
  normalizeMeshSchedulingStrategy: () => normalizeMeshSchedulingStrategy,
20906
20928
  normalizeMeshTaskMode: () => normalizeMeshTaskMode,
20907
20929
  normalizeMeshWorkerResult: () => normalizeMeshWorkerResult,
@@ -22241,6 +22263,7 @@ function getSavedProviderSessions(state, filters) {
22241
22263
  // src/index.ts
22242
22264
  init_mesh_config();
22243
22265
  init_dist();
22266
+ init_dist();
22244
22267
  init_coordinator_prompt();
22245
22268
  init_mesh_missions();
22246
22269
  init_mesh_task_stats();
@@ -27871,6 +27894,9 @@ function resolveLegacyProviderScript(fn, scriptName, params) {
27871
27894
  return fn() || null;
27872
27895
  }
27873
27896
 
27897
+ // src/commands/handler.ts
27898
+ init_hash();
27899
+
27874
27900
  // src/providers/manual-attendance.ts
27875
27901
  var AUTO_APPROVE_MANUAL_ATTENDANCE_SUPPRESS_MS = 6e4;
27876
27902
  var ManualAttendanceTracker = class {
@@ -32605,7 +32631,6 @@ var DaemonCommandHandler = class {
32605
32631
  const https = require("https");
32606
32632
  const fs35 = require("fs");
32607
32633
  const path42 = require("path");
32608
- const crypto6 = require("crypto");
32609
32634
  const REGISTRY = "https://api.adhf.dev/api/v1/registry";
32610
32635
  function fetchText(url, timeoutMs) {
32611
32636
  return new Promise((resolve24, reject) => {
@@ -32637,7 +32662,7 @@ var DaemonCommandHandler = class {
32637
32662
  `${REGISTRY}/providers/${encodeURIComponent(type)}/${encodeURIComponent(version)}/download`,
32638
32663
  3e4
32639
32664
  );
32640
- const actualChecksum = crypto6.createHash("sha256").update(manifestBody, "utf-8").digest("hex");
32665
+ const actualChecksum = sha256Hex(manifestBody);
32641
32666
  if (actualChecksum !== meta.checksum) {
32642
32667
  return { success: false, error: `checksum mismatch: expected ${meta.checksum}, got ${actualChecksum}` };
32643
32668
  }
@@ -34986,6 +35011,7 @@ var fs19 = __toESM(require("fs"));
34986
35011
  var import_node_module = require("module");
34987
35012
  init_contracts();
34988
35013
  init_provider_input_support();
35014
+ init_hash();
34989
35015
 
34990
35016
  // src/providers/spec/route.ts
34991
35017
  var fs18 = __toESM(require("fs"));
@@ -38672,7 +38698,7 @@ var CliProviderInstance = class _CliProviderInstance {
38672
38698
  if (!content) return;
38673
38699
  const receivedAt = Date.now();
38674
38700
  this.lastAcknowledgedUserInputAt = receivedAt;
38675
- const dedupKey = `user_input_ack:${crypto4.createHash("sha256").update(`${this.instanceId}:${content}:${receivedAt}`).digest("hex").slice(0, 24)}`;
38701
+ const dedupKey = `user_input_ack:${shortHash(`${this.instanceId}:${content}:${receivedAt}`, 24)}`;
38676
38702
  this.appendRuntimeMessage(buildChatMessage({
38677
38703
  role: "user",
38678
38704
  senderName: "User",
@@ -42537,6 +42563,7 @@ var fs25 = __toESM(require("fs"));
42537
42563
  var path34 = __toESM(require("path"));
42538
42564
  var os25 = __toESM(require("os"));
42539
42565
  var chokidar = __toESM(require("chokidar"));
42566
+ init_hash();
42540
42567
  init_logger();
42541
42568
 
42542
42569
  // src/providers/provider-schema.ts
@@ -45194,10 +45221,7 @@ var ProviderLoader = class _ProviderLoader {
45194
45221
  reject(new Error(`download timeout for ${type}`));
45195
45222
  });
45196
45223
  });
45197
- const actualChecksum = await new Promise((resolve24) => {
45198
- const crypto6 = require("crypto");
45199
- resolve24(crypto6.createHash("sha256").update(manifestBody, "utf-8").digest("hex"));
45200
- });
45224
+ const actualChecksum = sha256Hex(manifestBody);
45201
45225
  if (actualChecksum !== checksum) {
45202
45226
  this.log(`\u26A0 Registry checksum mismatch for ${type}@${version} \u2014 skipping`);
45203
45227
  continue;
@@ -60204,477 +60228,6 @@ var DevServer = class _DevServer {
60204
60228
  async handleAutoImplement(type, req, res) {
60205
60229
  return handleAutoImplement(this, type, req, res);
60206
60230
  }
60207
- buildAutoImplPrompt(type, provider, providerDir, functions, domContext, referenceScripts, userComment, referenceType) {
60208
- if (provider.category === "cli") {
60209
- return this.buildCliAutoImplPrompt(type, provider, providerDir, functions, referenceScripts, userComment, referenceType);
60210
- }
60211
- const lines = [];
60212
- lines.push("You are implementing browser automation scripts for an IDE provider.");
60213
- lines.push("Be concise. Do NOT explain your reasoning. Just edit files directly.");
60214
- lines.push("");
60215
- lines.push(`# Target: ${provider.name || type} (${type})`);
60216
- lines.push(`Provider directory: \`${providerDir}\``);
60217
- lines.push("");
60218
- const funcToFile = {
60219
- readChat: "read_chat.js",
60220
- sendMessage: "send_message.js",
60221
- resolveAction: "resolve_action.js",
60222
- listSessions: "list_sessions.js",
60223
- listChats: "list_chats.js",
60224
- switchSession: "switch_session.js",
60225
- newSession: "new_session.js",
60226
- focusEditor: "focus_editor.js",
60227
- openPanel: "open_panel.js",
60228
- listModels: "list_models.js",
60229
- listModes: "list_modes.js",
60230
- setModel: "set_model.js",
60231
- setMode: "set_mode.js"
60232
- };
60233
- const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
60234
- const scriptsDir = path41.join(providerDir, "scripts");
60235
- const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
60236
- if (latestScriptsDir) {
60237
- lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
60238
- lines.push("");
60239
- lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
60240
- lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
60241
- lines.push("");
60242
- for (const file of fs34.readdirSync(latestScriptsDir)) {
60243
- if (file.endsWith(".js") && targetFileNames.has(file)) {
60244
- try {
60245
- const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
60246
- lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
60247
- lines.push("```javascript");
60248
- lines.push(content);
60249
- lines.push("```");
60250
- lines.push("");
60251
- } catch {
60252
- }
60253
- }
60254
- }
60255
- const refFiles = fs34.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
60256
- if (refFiles.length > 0) {
60257
- lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
60258
- lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
60259
- lines.push("");
60260
- for (const file of refFiles) {
60261
- try {
60262
- const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
60263
- lines.push(`### \`${file}\` \u{1F512}`);
60264
- lines.push("```javascript");
60265
- lines.push(content);
60266
- lines.push("```");
60267
- lines.push("");
60268
- } catch {
60269
- }
60270
- }
60271
- }
60272
- }
60273
- if (domContext) {
60274
- lines.push("## Live DOM Analysis (from CDP)");
60275
- lines.push("Use these selectors in your implementations:");
60276
- lines.push("```json");
60277
- lines.push(JSON.stringify(domContext, null, 2));
60278
- lines.push("```");
60279
- lines.push("");
60280
- }
60281
- if (Object.keys(referenceScripts).length > 0) {
60282
- lines.push(`## Reference Implementation (from ${referenceType || "antigravity"} provider)`);
60283
- lines.push("These are WORKING scripts from another IDE. Adapt the PATTERNS (not selectors) for the target IDE.");
60284
- lines.push("");
60285
- for (const fn of functions) {
60286
- const fileName = funcToFile[fn];
60287
- if (fileName && referenceScripts[fileName]) {
60288
- lines.push(`### ${fn} \u2192 \`${fileName}\``);
60289
- lines.push("```javascript");
60290
- lines.push(referenceScripts[fileName]);
60291
- lines.push("```");
60292
- lines.push("");
60293
- }
60294
- }
60295
- if (referenceScripts["scripts.js"]) {
60296
- lines.push("### Router \u2192 `scripts.js`");
60297
- lines.push("```javascript");
60298
- lines.push(referenceScripts["scripts.js"]);
60299
- lines.push("```");
60300
- lines.push("");
60301
- }
60302
- }
60303
- const docsDir = path41.join(providerDir, "../../docs");
60304
- const loadGuide = (name) => {
60305
- try {
60306
- const p = path41.join(docsDir, name);
60307
- if (fs34.existsSync(p)) return fs34.readFileSync(p, "utf-8");
60308
- } catch {
60309
- }
60310
- return null;
60311
- };
60312
- const providerGuide = loadGuide("PROVIDER_GUIDE.md");
60313
- if (providerGuide) {
60314
- lines.push("## Documentation: PROVIDER_GUIDE.md");
60315
- lines.push("```markdown");
60316
- lines.push(providerGuide);
60317
- lines.push("```");
60318
- lines.push("");
60319
- }
60320
- const cdpGuide = loadGuide("CDP_SELECTOR_GUIDE.md");
60321
- if (cdpGuide) {
60322
- lines.push("## Documentation: CDP_SELECTOR_GUIDE.md");
60323
- lines.push("```markdown");
60324
- lines.push(cdpGuide);
60325
- lines.push("```");
60326
- lines.push("");
60327
- }
60328
- lines.push("## Task");
60329
- lines.push(`Edit files in \`${providerDir}\` to implement: **${functions.join(", ")}**`);
60330
- lines.push("");
60331
- lines.push("## Rules");
60332
- 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.');
60333
- lines.push("1. **Scripts WITHOUT params** \u2192 IIFE: `(() => { ... })()`");
60334
- lines.push("2. **Scripts WITH params** \u2192 arrow: `(params) => { ... }` \u2014 router calls `(${script})(${JSON.stringify(params)})`");
60335
- lines.push("3. If live DOM analysis is included above, use it. Otherwise, discover selectors yourself via CDP before coding.");
60336
- lines.push("4. Always wrap in try-catch, return `JSON.stringify(result)`");
60337
- lines.push("5. Do NOT modify `scripts.js` router \u2014 only edit individual `*.js` files");
60338
- lines.push("6. All scripts run in the browser (CDP evaluate) \u2014 use DOM APIs only");
60339
- 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.');
60340
- 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.");
60341
- lines.push("9. Do NOT delete any files. Implement the logic by replacing the empty stubs.");
60342
- lines.push("");
60343
- lines.push("## Required Return Format");
60344
- lines.push("| Function | Return JSON |");
60345
- lines.push("|---|---|");
60346
- 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 |");
60347
- lines.push("| sendMessage | `{ sent: false, needsTypeAndSend: true, selector }` |");
60348
- lines.push("| resolveAction | `{ resolved: true/false, clicked? }` |");
60349
- lines.push("| listSessions | `{ sessions: [{ id, title, active, index }] }` |");
60350
- lines.push("| switchSession | `{ switched: true/false }` |");
60351
- lines.push("| newSession | `{ created: true/false }` |");
60352
- lines.push("| listModels | `{ models: [{ name, id }], current }` |");
60353
- lines.push("| setModel | `{ success: true/false }` |");
60354
- lines.push("| listModes | `{ modes: [{ name, id }], current }` |");
60355
- lines.push("| setMode | `{ success: true/false }` |");
60356
- lines.push("| focusEditor | `{ focused: true/false, error? }` |");
60357
- lines.push("| openPanel | `{ opened: true/false, visible: true/false, focused?: true, error? }` |");
60358
- lines.push("");
60359
- lines.push("## \u{1F534} CRITICAL: readChat `status` Lifecycle");
60360
- lines.push("The `status` field in readChat controls how the dashboard and daemon auto-approve-loop behave.");
60361
- lines.push("Getting this wrong will break the entire automation pipeline. The status MUST reflect the ACTUAL current state:");
60362
- lines.push("");
60363
- lines.push("| Status | When to use | How to detect |");
60364
- lines.push("|---|---|---|");
60365
- lines.push("| `idle` | AI is NOT generating, no approval needed | Default state. No stop button, no spinners, no approval pills/buttons |");
60366
- 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) |');
60367
- lines.push("| `waiting_approval` | AI stopped and needs user action | Actionable buttons like Run/Skip/Accept/Reject are visible AND clickable |");
60368
- lines.push("");
60369
- lines.push("### \u26A0\uFE0F Status Detection Gotchas (MUST READ!)");
60370
- 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).`);
60371
- 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.');
60372
- 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.");
60373
- 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.');
60374
- 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`.");
60375
- lines.push("6. **activeModal must include actions**: When `status` is `waiting_approval`, the `activeModal` object MUST include a non-empty `actions` array.");
60376
- lines.push("");
60377
- lines.push("## Action");
60378
- lines.push("1. Edit the script files to implement working code");
60379
- lines.push("2. After editing, TEST each function using the DevConsole API (see below)");
60380
- lines.push("3. If a test fails, fix the implementation and re-test");
60381
- lines.push("4. **IMPORTANT VERIFICATION LOGIC**: When verifying your implementation, beware of state contamination! You MUST perform strict Integration Testing:");
60382
- 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.");
60383
- 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.");
60384
- lines.push(" - `switchSession`: Prove your switch was successful by subsequently calling `readChat` and explicitly checking that the chat context has actually changed.");
60385
- lines.push("");
60386
- lines.push("## DOM Exploration");
60387
- if (domContext) {
60388
- lines.push("A lightweight DOM snapshot is included above, but you MUST still verify selectors yourself before finalizing the scripts.");
60389
- } else {
60390
- lines.push("No DOM snapshot is included here. You MUST use your command-line tools to discover the IDE structure dynamically.");
60391
- }
60392
- lines.push("");
60393
- lines.push("### 1. Evaluate JS to explore IDE DOM");
60394
- lines.push("Use cURL to run JavaScript inside the IDE:");
60395
- lines.push("```bash");
60396
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cdp/evaluate \\`);
60397
- lines.push(` -H "Content-Type: application/json" \\`);
60398
- lines.push(` -d '{"expression": "document.body.innerHTML.substring(0, 1000)", "ideType": "${type}"}'`);
60399
- lines.push("```");
60400
- lines.push("");
60401
- lines.push("### 2. Test your generated function");
60402
- lines.push("Once you save the file, test it by running:");
60403
- lines.push("```bash");
60404
- lines.push(`curl -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/providers/reload`);
60405
- 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}"}'`);
60406
- lines.push("```");
60407
- lines.push("");
60408
- lines.push("### Task Workflow");
60409
- lines.push("1. Write bash scripts to `curl` the CDP evaluate API above to find exactly where `.chat-message`, etc., are located.");
60410
- lines.push("2. Iteratively explore until you are confident in your selectors.");
60411
- lines.push("3. Edit the `.js` files using the selectors you discovered.");
60412
- lines.push("4. Reload providers and TEST your script via the API.");
60413
- lines.push("");
60414
- lines.push("### \u{1F525} Advanced UI Parsing (CRUCIAL for `readChat`)");
60415
- 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.");
60416
- lines.push("To achieve this, you MUST generate a live test scenario:");
60417
- lines.push(`1. Early in your process, send a rich prompt to the IDE using the API:`);
60418
- 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"}}'\``);
60419
- lines.push("2. Wait a few seconds for the IDE AI to generate these elements in the UI.");
60420
- lines.push("3. Use CDP evaluate to deeply inspect the DOM structure of the newly generated tables, code blocks, thought blocks, and tool calls.");
60421
- lines.push("4. Ensure `readChat` extracts `content` with precise markdown formatting (especially for tables/code) and assigns correct `kind` tags (`thought`, `tool`, `terminal`).");
60422
- lines.push("");
60423
- lines.push("## \u{1F9EA} MANDATORY: Status Integration Test");
60424
- lines.push("Before finishing, you MUST run this end-to-end test to verify readChat status transitions work:");
60425
- lines.push("");
60426
- lines.push("### Step 1: Baseline \u2014 confirm idle");
60427
- lines.push("```bash");
60428
- lines.push(`curl -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/providers/reload`);
60429
- 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}"}')`);
60430
- 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')"`);
60431
- lines.push("```");
60432
- lines.push("");
60433
- lines.push("### Step 2: Send a LONG message that triggers extended generation (10+ seconds)");
60434
- lines.push("```bash");
60435
- 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."}}'`);
60436
- lines.push("sleep 3");
60437
- lines.push("```");
60438
- lines.push("");
60439
- lines.push("### Step 3: Check generating OR completed");
60440
- lines.push("The AI may still be generating OR may have finished already. Either generating or idle is acceptable:");
60441
- lines.push("```bash");
60442
- 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}"}')`);
60443
- 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}')"`);
60444
- lines.push("```");
60445
- lines.push("");
60446
- lines.push("### Step 4: Wait for completion and verify new message");
60447
- lines.push("```bash");
60448
- lines.push("sleep 10");
60449
- 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}"}')`);
60450
- 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)}')"`);
60451
- lines.push("```");
60452
- lines.push("");
60453
- lines.push("If ANY step fails, fix your implementation and re-run the test. Do NOT finish until all 4 steps pass.");
60454
- lines.push("");
60455
- if (userComment) {
60456
- lines.push("## \u26A0\uFE0F User Instructions (HIGH PRIORITY)");
60457
- lines.push("The user has provided the following additional instructions. Follow them strictly:");
60458
- lines.push("");
60459
- lines.push(userComment);
60460
- lines.push("");
60461
- }
60462
- lines.push("Start NOW. Do not ask for permission. Explore the DOM -> Code -> Test.");
60463
- return lines.join("\n");
60464
- }
60465
- buildCliAutoImplPrompt(type, provider, providerDir, functions, referenceScripts, userComment, referenceType) {
60466
- const lines = [];
60467
- lines.push("You are implementing PTY parsing scripts for a CLI provider.");
60468
- lines.push("Be concise. Do NOT explain your reasoning. Edit files directly and verify with the local DevServer.");
60469
- lines.push("");
60470
- lines.push(`# Target: ${provider.name || type} (${type})`);
60471
- lines.push(`Provider directory: \`${providerDir}\``);
60472
- lines.push("Provider category: `cli`");
60473
- lines.push("");
60474
- const funcToFile = {
60475
- parseSession: "parse_session.js",
60476
- detectStatus: "detect_status.js",
60477
- parseApproval: "parse_approval.js"
60478
- };
60479
- const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
60480
- const scriptsDir = path41.join(providerDir, "scripts");
60481
- const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
60482
- if (latestScriptsDir) {
60483
- lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
60484
- lines.push("");
60485
- lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
60486
- lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
60487
- lines.push("");
60488
- for (const file of fs34.readdirSync(latestScriptsDir)) {
60489
- if (!file.endsWith(".js")) continue;
60490
- if (!targetFileNames.has(file)) continue;
60491
- try {
60492
- const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
60493
- lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
60494
- lines.push("```javascript");
60495
- lines.push(content);
60496
- lines.push("```");
60497
- lines.push("");
60498
- } catch {
60499
- }
60500
- }
60501
- const refFiles = fs34.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
60502
- if (refFiles.length > 0) {
60503
- lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
60504
- lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
60505
- lines.push("");
60506
- for (const file of refFiles) {
60507
- try {
60508
- const content = fs34.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
60509
- lines.push(`### \`${file}\` \u{1F512}`);
60510
- lines.push("```javascript");
60511
- lines.push(content);
60512
- lines.push("```");
60513
- lines.push("");
60514
- } catch {
60515
- }
60516
- }
60517
- }
60518
- }
60519
- if (Object.keys(referenceScripts).length > 0) {
60520
- lines.push(`## Reference Implementation (from ${referenceType || "another CLI"} provider)`);
60521
- lines.push("These are working CLI PTY parser scripts. Reuse the parsing shape and runtime contract, but adapt to the target CLI screen.");
60522
- lines.push("");
60523
- for (const fn of functions) {
60524
- const fileName = funcToFile[fn];
60525
- if (fileName && referenceScripts[fileName]) {
60526
- lines.push(`### ${fn} \u2192 \`${fileName}\``);
60527
- lines.push("```javascript");
60528
- lines.push(referenceScripts[fileName]);
60529
- lines.push("```");
60530
- lines.push("");
60531
- }
60532
- }
60533
- if (referenceScripts["scripts.js"]) {
60534
- lines.push("### Router \u2192 `scripts.js`");
60535
- lines.push("```javascript");
60536
- lines.push(referenceScripts["scripts.js"]);
60537
- lines.push("```");
60538
- lines.push("");
60539
- }
60540
- }
60541
- const docsDir = path41.join(providerDir, "../../docs");
60542
- const loadGuide = (name) => {
60543
- try {
60544
- const p = path41.join(docsDir, name);
60545
- if (fs34.existsSync(p)) return fs34.readFileSync(p, "utf-8");
60546
- } catch {
60547
- }
60548
- return null;
60549
- };
60550
- const providerGuide = loadGuide("PROVIDER_GUIDE.md");
60551
- if (providerGuide) {
60552
- lines.push("## Documentation: PROVIDER_GUIDE.md");
60553
- lines.push("```markdown");
60554
- lines.push(providerGuide);
60555
- lines.push("```");
60556
- lines.push("");
60557
- }
60558
- lines.push("## Runtime Contract");
60559
- lines.push("The daemon runtime is already implemented in `packages/daemon-core/src/cli-adapters/provider-cli-adapter.ts`.");
60560
- lines.push("Your scripts receive PTY-derived input and must return plain JS objects.");
60561
- lines.push("");
60562
- lines.push("| Function | Input | Return |");
60563
- lines.push("|---|---|---|");
60564
- lines.push("| `parseSession` | `{ buffer, rawBuffer, recentBuffer, screenText, messages, partialResponse }` | `{ id, status, title, messages, activeModal }` |");
60565
- lines.push("| `detectStatus` | `{ tail, screenText, rawBuffer }` | `idle`, `generating`, `waiting_approval`, or `error` |");
60566
- lines.push("| `parseApproval` | `{ buffer, rawBuffer, tail }` | `{ message, buttons }` or `null` |");
60567
- lines.push("");
60568
- lines.push("## Primary Source of Truth");
60569
- lines.push("The runtime now provides a reliable current-screen snapshot. Treat `screenText` as the primary source of truth for the LIVE visible UI.");
60570
- lines.push("That means:");
60571
- lines.push("- Use `screenText` first for prompt detection, approval UI, status, and visible assistant content.");
60572
- lines.push("- Use `rawBuffer` only as supporting evidence when ANSI/style/cursor cues matter.");
60573
- lines.push("- Use `buffer` only when the visible screen does not contain enough text to recover the latest assistant answer.");
60574
- lines.push("- Do NOT build the parser around stale transcript noise if the current screen already gives the answer.");
60575
- lines.push("");
60576
- lines.push("## Rules");
60577
- 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.');
60578
- lines.push("1. These scripts run in Node.js CommonJS, not in the browser. Do NOT use DOM APIs.");
60579
- lines.push("2. Prefer `screenText` for current visible UI state. It is now the PTY equivalent of a trustworthy live DOM snapshot.");
60580
- lines.push("3. Use `messages` as prior transcript state so redraws do not duplicate old turns on every parse.");
60581
- lines.push("4. Use `partialResponse` for the actively streaming assistant text when status is `generating`.");
60582
- lines.push("5. `detectStatus` must stay lightweight and current-screen-oriented. Prefer the active bottom-of-screen region over stale history.");
60583
- lines.push("6. `parseApproval` should understand the live approval area and return clean button labels from the CURRENT visible modal.");
60584
- lines.push("7. Use `rawBuffer` only when ANSI/control-sequence artifacts or style cues matter. Do not depend on raw escape noise unless necessary.");
60585
- lines.push("8. Keep exports compatible with the existing `scripts.js` router (`module.exports = function ...`).");
60586
- 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.');
60587
- 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.");
60588
- lines.push("11. Do NOT repeatedly dump the same target files. Read the target scripts once, reproduce the bug, then move directly to patching.");
60589
- 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.");
60590
- 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.");
60591
- 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.");
60592
- 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.");
60593
- lines.push("");
60594
- lines.push("## Task");
60595
- lines.push(`Edit files in \`${providerDir}\` to implement: **${functions.join(", ")}**`);
60596
- lines.push("");
60597
- lines.push("## Verification API");
60598
- lines.push("Use the DevServer CLI debug endpoints, not DOM/CDP routes.");
60599
- lines.push("");
60600
- lines.push("### 1. Launch the target CLI");
60601
- lines.push("```bash");
60602
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/launch \\`);
60603
- lines.push(' -H "Content-Type: application/json" \\');
60604
- lines.push(` -d '{"type":"${type}","workingDir":"${providerDir.replace(/\\/g, "\\\\")}"}'`);
60605
- lines.push("```");
60606
- lines.push("");
60607
- lines.push("### 2. Inspect parsed + raw adapter state");
60608
- lines.push("```bash");
60609
- lines.push(`curl -sS http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/debug/${type}`);
60610
- lines.push(`curl -sS http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/trace/${type}`);
60611
- lines.push(`curl -sS http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/status`);
60612
- lines.push("```");
60613
- lines.push("");
60614
- lines.push("The debug payload should be read in this priority order:");
60615
- lines.push("1. `screenText` / current visible state");
60616
- lines.push("2. parsed `status`, `messages`, `activeModal`");
60617
- lines.push("3. `rawBuffer` only for style/control-sequence cues");
60618
- lines.push("4. `buffer` only when the current screen is insufficient");
60619
- lines.push("");
60620
- lines.push("Extract the current `instanceId` from the launch or status response and keep using it below.");
60621
- lines.push("");
60622
- lines.push("### 3. Send a realistic approval-triggering prompt");
60623
- lines.push("```bash");
60624
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/send \\`);
60625
- lines.push(' -H "Content-Type: application/json" \\');
60626
- 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."}'`);
60627
- lines.push("```");
60628
- lines.push("");
60629
- lines.push("### 4. If approval appears, resolve it until the CLI reaches idle");
60630
- lines.push("```bash");
60631
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/resolve \\`);
60632
- lines.push(' -H "Content-Type: application/json" \\');
60633
- lines.push(` -d '{"type":"${type}","instanceId":"<INSTANCE_ID>","buttonIndex":0}'`);
60634
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/raw \\`);
60635
- lines.push(' -H "Content-Type: application/json" \\');
60636
- lines.push(` -d '{"type":"${type}","instanceId":"<INSTANCE_ID>","keys":"1"}'`);
60637
- lines.push("```");
60638
- lines.push("");
60639
- 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.");
60640
- lines.push("");
60641
- lines.push("### Patch Discipline");
60642
- 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.");
60643
- lines.push("");
60644
- lines.push("### 5. Verify the side effects outside the CLI");
60645
- lines.push("```bash");
60646
- lines.push("test -f tmp/adhdev_provider_fix_test.py");
60647
- lines.push("python3 tmp/adhdev_provider_fix_test.py");
60648
- lines.push("```");
60649
- lines.push("");
60650
- lines.push("### 6. Stop the CLI when finished");
60651
- lines.push("```bash");
60652
- lines.push(`curl -sS -X POST http://127.0.0.1:${DEV_SERVER_PORT}/api/cli/stop \\`);
60653
- lines.push(' -H "Content-Type: application/json" \\');
60654
- lines.push(` -d '{"type":"${type}","instanceId":"<INSTANCE_ID>"}'`);
60655
- lines.push("```");
60656
- lines.push("");
60657
- lines.push("## Required Validation");
60658
- lines.push("1. Confirm `detectStatus` changes sensibly between startup, generating, approval, and idle.");
60659
- lines.push("2. Confirm `parseSession` produces a stable transcript without duplicating past turns when the PTY redraws.");
60660
- lines.push("3. Confirm the latest assistant message streams through `partialResponse` while generation is in progress.");
60661
- lines.push("4. Confirm approval parsing returns meaningful button labels when the CLI requests permission.");
60662
- lines.push("5. Confirm the Python file was actually created and executed, not just described in chat text.");
60663
- lines.push("6. Confirm the final assistant transcript includes the exact Python output, including the working directory line and the five square numbers.");
60664
- lines.push("7. Re-run the debug endpoints after edits. Do NOT finish until the parsed result looks correct.");
60665
- lines.push("8. Confirm the parser still works after a redraw or scroll change without duplicating transcript history.");
60666
- lines.push("9. Confirm the implementation prefers current-screen signals over stale history when both are present.");
60667
- lines.push("");
60668
- if (userComment) {
60669
- lines.push("## \u26A0\uFE0F User Instructions (HIGH PRIORITY)");
60670
- lines.push("The user has provided the following additional instructions. Follow them strictly:");
60671
- lines.push("");
60672
- lines.push(userComment);
60673
- lines.push("");
60674
- }
60675
- lines.push("Start NOW. Launch the CLI, inspect PTY state, edit the scripts, and verify via the CLI debug endpoints.");
60676
- return lines.join("\n");
60677
- }
60678
60231
  handleAutoImplSSE(type, req, res) {
60679
60232
  handleAutoImplSSE(this, type, req, res);
60680
60233
  }
@@ -62551,6 +62104,7 @@ var V1_CONTRACT_VERSION = "1.0.0";
62551
62104
  markSetupComplete,
62552
62105
  markStaleDirectDispatches,
62553
62106
  maybeRunDaemonUpgradeHelperFromEnv,
62107
+ meshNodeIdMatches,
62554
62108
  namedKeyToAnsi,
62555
62109
  namedKeysToAnsi,
62556
62110
  nodeSatisfiesRequiredTags,
@@ -62567,6 +62121,7 @@ var V1_CONTRACT_VERSION = "1.0.0";
62567
62121
  normalizeManagedStatus,
62568
62122
  normalizeMeshCapabilityTags,
62569
62123
  normalizeMeshDaemonRole,
62124
+ normalizeMeshNodeId,
62570
62125
  normalizeMeshSchedulingStrategy,
62571
62126
  normalizeMeshTaskMode,
62572
62127
  normalizeMeshWorkerResult,