pokt-cli 1.0.10 → 1.0.11

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/chat/loop.js CHANGED
@@ -21,7 +21,8 @@ CORE CAPABILITIES:
21
21
  3. **Problem Solving**: You analyze errors and propose/apply fixes.
22
22
 
23
23
  FUNCTION CALLING (native tools — USE THEM):
24
- - This chat uses OpenAI-style **tool_calls**. You MUST use the provided functions for actions: \`read_file\`, \`write_file\`, \`run_command\`, \`list_files\`, etc., and any tool whose name starts with \`mcp_\`.
24
+ - This chat uses OpenAI-style **tool_calls**. You MUST use the provided functions for actions: \`read_file\`, \`search_replace\`, \`write_file\`, \`run_command\`, \`list_files\`, etc., and any tool whose name starts with \`mcp_\`.
25
+ - **Edits vs rewrites**: For modifying existing files, prefer \`search_replace\` (old_string, new_string, path) — targeted, minimal changes. Use \`write_file\` only for new files or full rewrites. Always call \`read_file\` first to get exact content before \`search_replace\`.
25
26
  - **Avoid** shell lines like \`mcp_Something_tool "..."\` in markdown — the CLI may run them as **fallback** if they match a registered tool, but **native tool_calls are always better** (correct args, one round-trip).
26
27
  - For databases/APIs exposed via MCP, call the real \`mcp_*\` tools with the correct JSON arguments (e.g. Neon: run SQL via the server's SQL tool, not a invented command name).
27
28
  - **Neon MCP**: tools like \`get_database_tables\`, \`describe_project\`, \`list_branch_computes\` need \`projectId\`. Call \`list_projects\` first and pass the \`id\` of the target project, or rely on the CLI: if your account has exactly one project, Pokt may inject \`projectId\` automatically. To list logical Postgres databases, prefer \`run_sql\` with \`SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY 1;\`.
@@ -34,6 +35,7 @@ WHEN THE MODEL DOES NOT RETURN tool_calls (rare):
34
35
 
35
36
  GUIDELINES:
36
37
  - You will receive the user request first, then the current project structure. Use the project structure to understand the context before creating or editing anything.
38
+ - **Session file focus**: User messages may include a \`[Pokt]\` line with the last path used via \`read_file\` / \`write_file\`. If the user asks to modify, migrate, or rewrite "the" script/app without naming a file, call \`read_file\` on that path and then \`write_file\` to the **same** path. Do **not** switch to \`main.py\` or another new name unless the user explicitly asks.
37
39
  - When asked to fix something, first **read** the relevant files to understand the context.
38
40
  - When creating a project, start by planning the structure, then use \`write_file\` (tool call) to create each file.
39
41
  - You have full access to the current terminal via \`run_command\` for \`npm install\`, \`tsc\`, etc. You may also emit **scripts executáveis** (Node, Python, npx, \`psql\`, etc.) via \`run_command\` when MCP não estiver disponível ou o usuário pedir código para rodar localmente.
@@ -69,6 +71,45 @@ async function loadProjectStructure() {
69
71
  }
70
72
  }
71
73
  }
74
+ /** Detecta se o usuário está pedindo modificação/migração em projeto existente (como gemini-cli faz). */
75
+ function suggestsProjectModification(userInput) {
76
+ const lower = userInput.toLowerCase().trim();
77
+ const modificationKeywords = [
78
+ 'mudar', 'alterar', 'mudança', 'alteração', 'migrar', 'migração', 'trocar', 'converter',
79
+ 'converta', 'modificar', 'refatorar', 'atualizar', 'substituir', 'troque', 'mude',
80
+ 'change', 'migrate', 'convert', 'modify', 'refactor', 'update', 'replace', 'switch',
81
+ ];
82
+ return modificationKeywords.some((kw) => lower.includes(kw));
83
+ }
84
+ /** Extrai arquivos .py da estrutura do projeto (list_files retorna paths separados por newline). */
85
+ function extractPyFilesFromStructure(structure) {
86
+ const lines = structure.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
87
+ return lines.filter((p) => /\.py$/i.test(p) && !p.includes('node_modules') && !p.includes('.git'));
88
+ }
89
+ /** Infere o arquivo alvo para edição quando usuário pede modificar "calculadora", "app", etc. */
90
+ function inferTargetFileFromProject(projectStructure, userInput) {
91
+ const pyFiles = extractPyFilesFromStructure(projectStructure);
92
+ if (pyFiles.length === 0)
93
+ return null;
94
+ const lower = userInput.toLowerCase();
95
+ // Palavras-chave que podem indicar o nome do arquivo
96
+ const keywords = ['calculadora', 'calculator', 'app', 'aplicativo', 'script', 'arquivo', 'projeto'];
97
+ for (const kw of keywords) {
98
+ if (lower.includes(kw)) {
99
+ const stem = kw.replace(/a$/, ''); // calculadora -> calculador
100
+ const match = pyFiles.find((f) => {
101
+ const base = f.replace(/\\/g, '/').split('/').pop()?.replace(/\.py$/, '') ?? '';
102
+ return base.toLowerCase().includes(kw) || base.toLowerCase().includes(stem);
103
+ });
104
+ if (match)
105
+ return match;
106
+ }
107
+ }
108
+ // Se só tem um .py no projeto, é provavelmente o alvo
109
+ if (pyFiles.length === 1)
110
+ return pyFiles[0];
111
+ return null;
112
+ }
72
113
  export async function startChatLoop(modelConfig) {
73
114
  let activeModel = modelConfig;
74
115
  let client = await getClient(activeModel);
@@ -190,6 +231,11 @@ Comandos do chat:
190
231
  `));
191
232
  }
192
233
  let lastAssistantText = '';
234
+ /** Último caminho relativo usado em read_file/write_file pelas tool_calls do assistente (foco da sessão). */
235
+ const sessionFileCtx = {
236
+ lastFocusedRelativePath: null,
237
+ suggestedModificationTarget: null,
238
+ };
193
239
  async function handleChatCommand(raw) {
194
240
  const parts = raw.trim().split(/\s+/);
195
241
  const cmd = parts[0].toLowerCase();
@@ -337,17 +383,36 @@ Atalhos:
337
383
  `));
338
384
  continue;
339
385
  }
340
- messages.push({ role: 'user', content: userInput });
386
+ let userContent = userInput;
387
+ if (sessionFileCtx.lastFocusedRelativePath) {
388
+ userContent = `${userInput}\n\n[Pokt] Último arquivo usado com read_file/write_file/search_replace nesta sessão: \`${sessionFileCtx.lastFocusedRelativePath}\`. Para alterar esse trabalho sem o usuário citar o nome, leia esse caminho e edite com search_replace ou write_file no mesmo caminho — não crie outro arquivo (ex.: main.py) por padrão.]`;
389
+ }
390
+ messages.push({ role: 'user', content: userContent });
341
391
  saveAuto(messages);
342
- // Primeiro o modelo o pedido; depois carregamos a estrutura do projeto para ele entender e então criar/editar
392
+ // Injeta estrutura do projeto para o modelo entender o contexto (como gemini-cli verifica antes de editar)
393
+ // Sempre na 1ª mensagem; também quando pedido sugere modificação/migração em projeto existente
343
394
  const isFirstUserMessage = messages.filter(m => m.role === 'user').length === 1;
344
- if (isFirstUserMessage) {
345
- const loadSpinner = ora('Carregando estrutura do projeto...').start();
395
+ const needsProjectContext = isFirstUserMessage || suggestsProjectModification(userInput);
396
+ if (needsProjectContext) {
397
+ const loadSpinner = ora('Verificando estrutura do projeto...').start();
346
398
  const projectStructure = await loadProjectStructure();
347
399
  loadSpinner.stop();
348
- messages.push({ role: 'system', content: `Current Project Structure:\n${projectStructure}` });
400
+ const targetFile = suggestsProjectModification(userInput)
401
+ ? inferTargetFileFromProject(projectStructure, userInput)
402
+ : null;
403
+ if (targetFile) {
404
+ sessionFileCtx.suggestedModificationTarget = targetFile;
405
+ }
406
+ let structureHint = '[Pokt] Use list_files/read_file para confirmar arquivos existentes. Para modificar: leia com read_file, edite com search_replace ou write_file no MESMO caminho — NÃO crie main.py ou novo projeto.';
407
+ if (targetFile) {
408
+ structureHint += ` OBRIGATÓRIO: o arquivo a editar é \`${targetFile}\`. Use tool_calls em \`${targetFile}\`, NUNCA em main.py.`;
409
+ }
410
+ messages.push({
411
+ role: 'system',
412
+ content: `Current Project Structure:\n${projectStructure}\n\n${structureHint}`,
413
+ });
349
414
  }
350
- await processLLMResponse(client, activeModel.id, messages, toolsForApi);
415
+ await processLLMResponse(client, activeModel.id, messages, toolsForApi, sessionFileCtx);
351
416
  // Atualiza auto-save após resposta
352
417
  saveAuto(messages);
353
418
  // Captura última resposta do assistente para /copy (melhor esforço)
@@ -451,9 +516,12 @@ function looksLikeFakeMcpInvocation(code) {
451
516
  * Extrai blocos de código da resposta (```lang\n...\n```) e, se encontrar
452
517
  * um nome de arquivo mencionado antes do bloco, aplica write_file.
453
518
  */
454
- /** Remove markdown/formatting do nome de arquivo (ex: **hello.py** → hello.py). */
519
+ /** Remove markdown/formatting do nome de arquivo (ex: **hello.py** → hello.py, (main.py → main.py). */
455
520
  function cleanFilename(candidate) {
456
- return candidate.replace(/^[\s*`'"]+/g, '').replace(/[\s*`'")\]\s]+$/g, '').trim();
521
+ return candidate
522
+ .replace(/^[\s*`'"(\[]+/g, '')
523
+ .replace(/[\s*`'")\]\s]+$/g, '')
524
+ .trim();
457
525
  }
458
526
  /**
459
527
  * Aplica blocos de código da resposta e retorna conteúdo para exibição (sem repetir o código).
@@ -471,7 +539,70 @@ function messageContentToString(content) {
471
539
  }
472
540
  return content != null ? String(content) : '';
473
541
  }
474
- async function applyCodeBlocksFromContent(content) {
542
+ function getFirstChoiceMessage(completion) {
543
+ const msg = completion.choices?.[0]?.message;
544
+ return msg ?? null;
545
+ }
546
+ function trackToolPathFocus(name, argsStr, ctx) {
547
+ if (name !== 'read_file' && name !== 'write_file' && name !== 'search_replace')
548
+ return;
549
+ try {
550
+ const args = JSON.parse(argsStr);
551
+ if (typeof args.path === 'string' && args.path.trim()) {
552
+ ctx.lastFocusedRelativePath = args.path.replace(/\\/g, '/').trim();
553
+ }
554
+ }
555
+ catch {
556
+ /* ignore */
557
+ }
558
+ }
559
+ /**
560
+ * Se o fallback iria gravar em generated.* mas já há um arquivo “foco” na sessão com a mesma extensão,
561
+ * reutiliza esse caminho (evita criar generated.py ao lado de calculadora.py).
562
+ */
563
+ function preferSessionPathOverGenerated(resolvedPath, ctx) {
564
+ const sessionLast = ctx?.lastFocusedRelativePath ?? null;
565
+ const suggested = ctx?.suggestedModificationTarget ?? null;
566
+ // Quando usuário pediu modificar e há arquivo inferido, NUNCA criar main.py/generated.py
567
+ if (suggested && /^(main|generated)\./i.test(resolvedPath)) {
568
+ return suggested.replace(/\\/g, '/');
569
+ }
570
+ if (!sessionLast || !/^generated\./i.test(resolvedPath))
571
+ return resolvedPath;
572
+ const suffix = resolvedPath.slice(resolvedPath.indexOf('.') + 1).toLowerCase();
573
+ const normLast = sessionLast.replace(/\\/g, '/').toLowerCase();
574
+ const extensionsForSuffix = {
575
+ py: ['.py'],
576
+ python: ['.py'],
577
+ js: ['.js'],
578
+ javascript: ['.js'],
579
+ mjs: ['.mjs'],
580
+ cjs: ['.cjs'],
581
+ ts: ['.ts', '.tsx'],
582
+ typescript: ['.ts', '.tsx'],
583
+ tsx: ['.tsx'],
584
+ jsx: ['.jsx'],
585
+ java: ['.java'],
586
+ go: ['.go'],
587
+ rs: ['.rs'],
588
+ html: ['.html', '.htm'],
589
+ css: ['.css'],
590
+ json: ['.json'],
591
+ md: ['.md', '.markdown'],
592
+ txt: ['.txt'],
593
+ cpp: ['.cpp', '.cc', '.cxx'],
594
+ c: ['.c'],
595
+ rb: ['.rb'],
596
+ php: ['.php'],
597
+ };
598
+ const exts = extensionsForSuffix[suffix];
599
+ if (exts?.some((e) => normLast.endsWith(e)))
600
+ return sessionLast.replace(/\\/g, '/');
601
+ if (normLast.endsWith('.' + suffix))
602
+ return sessionLast.replace(/\\/g, '/');
603
+ return resolvedPath;
604
+ }
605
+ async function applyCodeBlocksFromContent(content, sessionFileCtx) {
475
606
  const codeBlockRe = /```(\w*)\n([\s\S]*?)```/g;
476
607
  const appliedBlocks = [];
477
608
  let applied = false;
@@ -495,7 +626,10 @@ async function applyCodeBlocksFromContent(content) {
495
626
  const fileMatch = beforeBlock.match(/(\S+\.(?:py|js|ts|tsx|jsx|html|css|json|md|txt|java|go|rs|c|cpp|rb|php))(?=\s|$|[:.)\]*`"])/gi);
496
627
  const rawCandidate = fileMatch ? fileMatch[fileMatch.length - 1].trim() : null;
497
628
  const candidate = rawCandidate ? cleanFilename(rawCandidate) : null;
498
- const path = candidate && CODE_EXT.test(candidate) ? candidate : (lang === 'python' ? 'generated.py' : lang ? `generated.${lang}` : null);
629
+ let path = candidate && CODE_EXT.test(candidate) ? candidate : lang === 'python' ? 'generated.py' : lang ? `generated.${lang}` : null;
630
+ if (path) {
631
+ path = preferSessionPathOverGenerated(path, sessionFileCtx);
632
+ }
499
633
  if (path && isFallbackPathBlocked(path))
500
634
  continue;
501
635
  if (path &&
@@ -513,6 +647,8 @@ async function applyCodeBlocksFromContent(content) {
513
647
  }
514
648
  await executeTool('write_file', JSON.stringify({ path, content: code }));
515
649
  applied = true;
650
+ if (sessionFileCtx)
651
+ sessionFileCtx.lastFocusedRelativePath = path.replace(/\\/g, '/');
516
652
  appliedBlocks.push({ start: index, end: index + fullMatch.length, path });
517
653
  }
518
654
  catch {
@@ -556,7 +692,7 @@ async function createCompletionWithRetry(client, modelId, messages, toolsList, t
556
692
  /**
557
693
  * Executa todas as rodadas de tool_calls até o modelo devolver mensagem sem ferramentas.
558
694
  */
559
- async function drainToolCalls(client, modelId, messages, toolsList, startMessage, spinner) {
695
+ async function drainToolCalls(client, modelId, messages, toolsList, startMessage, spinner, sessionFileCtx) {
560
696
  let message = startMessage;
561
697
  let writeFileExecuted = false;
562
698
  let anyToolExecuted = false;
@@ -567,11 +703,12 @@ async function drainToolCalls(client, modelId, messages, toolsList, startMessage
567
703
  for (const toolCall of message.tool_calls) {
568
704
  anyToolExecuted = true;
569
705
  const name = toolCall.function.name;
570
- if (name === 'write_file')
706
+ if (name === 'write_file' || name === 'search_replace')
571
707
  writeFileExecuted = true;
572
708
  if (isMcpTool(name))
573
709
  mcpToolExecuted = true;
574
710
  const args = toolCall.function.arguments ?? '{}';
711
+ trackToolPathFocus(name, args, sessionFileCtx);
575
712
  const isMcp = isMcpTool(name);
576
713
  if (isMcp && !verbose) {
577
714
  console.log(ui.dim(`[MCP] ${name}…`));
@@ -602,17 +739,28 @@ async function drainToolCalls(client, modelId, messages, toolsList, startMessage
602
739
  spinner.start('Thinking...');
603
740
  const completion = await createCompletionWithRetry(client, modelId, messages, toolsList, 'auto');
604
741
  spinner.stop();
605
- message = completion.choices[0].message;
742
+ const nextMsg = getFirstChoiceMessage(completion);
743
+ if (!nextMsg) {
744
+ throw new Error('Resposta da API sem choices após execução de ferramentas.');
745
+ }
746
+ message = nextMsg;
606
747
  }
607
748
  return { message, writeFileExecuted, anyToolExecuted, mcpToolExecuted };
608
749
  }
609
- async function processLLMResponse(client, modelId, messages, toolsList) {
750
+ async function processLLMResponse(client, modelId, messages, toolsList, sessionFileCtx) {
610
751
  const spinner = ora('Thinking...').start();
611
752
  try {
612
753
  let completion = await createCompletionWithRetry(client, modelId, messages, toolsList);
613
- let message = completion.choices[0].message;
754
+ const first = getFirstChoiceMessage(completion);
755
+ if (!first) {
756
+ spinner.stop();
757
+ console.log(ui.error('\nResposta da API sem choices/mensagem. Tente novamente ou outro modelo.'));
758
+ messages.pop();
759
+ return;
760
+ }
761
+ let message = first;
614
762
  spinner.stop();
615
- const drained = await drainToolCalls(client, modelId, messages, toolsList, message, spinner);
763
+ const drained = await drainToolCalls(client, modelId, messages, toolsList, message, spinner, sessionFileCtx);
616
764
  message = drained.message;
617
765
  let writeFileExecutedThisTurn = drained.writeFileExecuted;
618
766
  let anyToolExecutedThisTurn = drained.anyToolExecuted;
@@ -640,14 +788,20 @@ async function processLLMResponse(client, modelId, messages, toolsList) {
640
788
  contentStr = mcpFromText.augmentedAssistantText;
641
789
  finalContent = mcpFromText.augmentedAssistantText;
642
790
  }
643
- // Resposta completamente vazia: recuperação (tool_choice required) + dreno + MCP em texto + SQL automático
791
+ // Resposta completamente vazia: recuperação (tool_choice required)
644
792
  if (!contentStr.trim() && toolsList.length > 0) {
645
- messages.push({
646
- role: 'system',
647
- content: '[Pokt recuperação] A última resposta veio vazia (sem texto útil). Responda em português. ' +
648
- 'Use tool_calls: para listar bancos PostgreSQL use mcp_*_run_sql com {"sql":"SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY 1;"}. ' +
649
- 'Alternativa: run_command com script executável (node, python, npx, psql). Nunca devolva corpo vazio.',
650
- });
793
+ const lastUserMsg = [...messages].reverse().find((m) => m.role === 'user');
794
+ const lastUserContent = typeof lastUserMsg?.content === 'string' ? lastUserMsg.content : '';
795
+ const isModificationRequest = suggestsProjectModification(lastUserContent);
796
+ let recoveryHint = '[Pokt recuperação] A última resposta veio vazia. Responda em português. Use tool_calls. Nunca devolva corpo vazio. ';
797
+ if (isModificationRequest) {
798
+ recoveryHint +=
799
+ 'O usuário pediu modificação em projeto existente: chame list_files para ver arquivos, read_file no arquivo relevante, depois search_replace ou write_file no MESMO caminho. NÃO crie projeto novo. ';
800
+ }
801
+ recoveryHint +=
802
+ 'Para bancos PostgreSQL: mcp_*_run_sql com {"sql":"SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY 1;"}. ' +
803
+ 'Alternativa: run_command com script (node, python, npx, psql).';
804
+ messages.push({ role: 'system', content: recoveryHint });
651
805
  spinner.start('Recuperando resposta vazia…');
652
806
  let recovery;
653
807
  try {
@@ -657,7 +811,13 @@ async function processLLMResponse(client, modelId, messages, toolsList) {
657
811
  recovery = await createCompletionWithRetry(client, modelId, messages, toolsList, 'auto');
658
812
  }
659
813
  spinner.stop();
660
- const drained2 = await drainToolCalls(client, modelId, messages, toolsList, recovery.choices[0].message, spinner);
814
+ const recoveryFirst = getFirstChoiceMessage(recovery);
815
+ if (!recoveryFirst) {
816
+ console.log(ui.error('\nResposta da API sem choices na recuperação. Tente outro modelo.'));
817
+ messages.pop();
818
+ return;
819
+ }
820
+ const drained2 = await drainToolCalls(client, modelId, messages, toolsList, recoveryFirst, spinner, sessionFileCtx);
661
821
  message = drained2.message;
662
822
  writeFileExecutedThisTurn = writeFileExecutedThisTurn || drained2.writeFileExecuted;
663
823
  anyToolExecutedThisTurn = anyToolExecutedThisTurn || drained2.anyToolExecuted;
@@ -693,27 +853,33 @@ async function processLLMResponse(client, modelId, messages, toolsList) {
693
853
  }
694
854
  // Quando a API não executa tools, tentar aplicar blocos de código da resposta
695
855
  if (!writeFileExecutedThisTurn) {
696
- let result = await applyCodeBlocksFromContent(contentStr);
856
+ let result = await applyCodeBlocksFromContent(contentStr, sessionFileCtx);
697
857
  // Se a IA só disse "We will call read_file/write_file" e não há código, pedir o código em um follow-up
698
- const looksLikeToolIntentOnly = /(We will call|We need to call|Let's call|I will call)\s+(read_file|write_file|run_command)/i.test(contentStr)
699
- || (/call\s+(read_file|write_file)/i.test(contentStr) && contentStr.length < 400);
858
+ const looksLikeToolIntentOnly = /(We will call|We need to call|Let's call|I will call)\s+(read_file|search_replace|write_file|run_command)/i.test(contentStr)
859
+ || (/call\s+(read_file|search_replace|write_file)/i.test(contentStr) && contentStr.length < 400);
700
860
  if (!result.applied && looksLikeToolIntentOnly) {
701
861
  messages.push({ role: 'assistant', content: rawContent ?? contentStr });
702
- const followUpSystem = `You replied as if tools would run in text only. Use tool_calls for read_file/write_file/run_command/mcp_* when possible. If you must output a file as markdown only: mention the filename then a full \`\`\`lang\`\`\` block — never use fake shell lines like mcp_Foo_bar. Do that now for the user's last request.`;
862
+ const followUpSystem = `You replied as if tools would run in text only. Use tool_calls for read_file/search_replace/write_file/run_command/mcp_* when possible. Prefer search_replace for edits. If you must output a file as markdown only: mention the filename then a full \`\`\`lang\`\`\` block — never use fake shell lines like mcp_Foo_bar. Do that now for the user's last request.`;
703
863
  messages.push({ role: 'system', content: followUpSystem });
704
864
  spinner.start('Getting code...');
705
865
  const followUp = await createCompletionWithRetry(client, modelId, messages, toolsList);
706
866
  spinner.stop();
707
- const followUpMsg = followUp.choices[0].message;
708
- const followUpStr = messageContentToString(followUpMsg.content);
709
- if (followUpStr.trim() !== '') {
710
- result = await applyCodeBlocksFromContent(followUpStr);
711
- contentStr = followUpStr;
712
- finalContent = followUpMsg.content ?? followUpStr;
713
- messages.push({ role: 'assistant', content: finalContent });
867
+ const followUpMsg = getFirstChoiceMessage(followUp);
868
+ if (!followUpMsg) {
869
+ console.log(ui.error('\nFollow-up da API sem choices/mensagem.'));
870
+ messages.push({ role: 'assistant', content: '' });
714
871
  }
715
872
  else {
716
- messages.push({ role: 'assistant', content: '' });
873
+ const followUpStr = messageContentToString(followUpMsg.content);
874
+ if (followUpStr.trim() !== '') {
875
+ result = await applyCodeBlocksFromContent(followUpStr, sessionFileCtx);
876
+ contentStr = followUpStr;
877
+ finalContent = followUpMsg.content ?? followUpStr;
878
+ messages.push({ role: 'assistant', content: finalContent });
879
+ }
880
+ else {
881
+ messages.push({ role: 'assistant', content: '' });
882
+ }
717
883
  }
718
884
  }
719
885
  if (contentStr.trim() !== '') {
@@ -726,7 +892,13 @@ async function processLLMResponse(client, modelId, messages, toolsList) {
726
892
  }
727
893
  else {
728
894
  console.log('\n' + ui.labelPokt());
729
- console.log(ui.dim('(Sem resposta da IA após recuperação. Tente: outro modelo em /model, ou peça explicitamente “chame mcp_Neon_run_sql com SELECT datname FROM pg_database…”, ou use run_command com psql/node.)'));
895
+ const lastUser = [...messages].reverse().find((m) => m.role === 'user');
896
+ const lastContent = typeof lastUser?.content === 'string' ? lastUser.content : '';
897
+ const isMod = suggestsProjectModification(lastContent);
898
+ const hint = isMod
899
+ ? '(Sem resposta da IA. Para modificar projeto: peça "liste os arquivos e leia o arquivo". Tente /model.)'
900
+ : '(Sem resposta da IA após recuperação. Tente: /model, ou peça mcp_Neon_run_sql, ou run_command.)';
901
+ console.log(ui.dim(hint));
730
902
  messages.push({ role: 'assistant', content: '' });
731
903
  }
732
904
  }
@@ -30,6 +30,56 @@ function looksLikeMcpJsonDump(s) {
30
30
  }
31
31
  return false;
32
32
  }
33
+ /**
34
+ * When exact old_string is not found, try to find a similar region and return helpful error.
35
+ * Inspired by gemini-cli fuzzy matcher fallback.
36
+ */
37
+ function findClosestMatchAndBuildError(fileContent, oldString, filePath) {
38
+ const oldLines = oldString.split('\n').filter((l) => l.trim().length > 0);
39
+ if (oldLines.length === 0) {
40
+ return `search_replace failed: old_string is empty or only whitespace.`;
41
+ }
42
+ const firstLine = oldLines[0];
43
+ const idx = fileContent.indexOf(firstLine);
44
+ if (idx >= 0) {
45
+ const start = Math.max(0, idx - 200);
46
+ const end = Math.min(fileContent.length, idx + firstLine.length + 400);
47
+ const snippet = fileContent.slice(start, end);
48
+ const diffResult = diff.diffLines(oldString, snippet);
49
+ const diffPreview = diffResult
50
+ .slice(0, 8)
51
+ .map((p) => (p.added ? `+${p.value}` : p.removed ? `-${p.value}` : ` ${p.value}`))
52
+ .join('')
53
+ .slice(0, 600);
54
+ return `search_replace failed: old_string not found exactly. First line was found at position ${idx}. Suggestion: check whitespace, indentation, line endings. Diff (expected vs file snippet):\n${diffPreview}\n\nCall read_file to see full content and retry with exact match.`;
55
+ }
56
+ const norm = (s) => s.replace(/\r\n/g, '\n').replace(/\s+/g, ' ').trim();
57
+ const normOld = norm(oldString);
58
+ const fileLines = fileContent.split('\n');
59
+ let bestLineIdx = -1;
60
+ let bestLen = 0;
61
+ for (let i = 0; i < fileLines.length; i++) {
62
+ const lineNorm = norm(fileLines[i]);
63
+ if (lineNorm.length < 10)
64
+ continue;
65
+ let matchLen = 0;
66
+ for (let j = 0; j < Math.min(lineNorm.length, normOld.length); j++) {
67
+ if (lineNorm[j] === normOld[j])
68
+ matchLen++;
69
+ else
70
+ break;
71
+ }
72
+ if (matchLen > bestLen && matchLen >= 15) {
73
+ bestLen = matchLen;
74
+ bestLineIdx = i;
75
+ }
76
+ }
77
+ if (bestLineIdx >= 0) {
78
+ const ctx = fileLines.slice(Math.max(0, bestLineIdx - 2), bestLineIdx + 4).join('\n');
79
+ return `search_replace failed: old_string not found. Closest region (line ${bestLineIdx + 1}):\n---\n${ctx}\n---\nUse read_file("${filePath}") and retry with exact content including indentation and newlines.`;
80
+ }
81
+ return `search_replace failed: old_string not found in ${filePath}. Use read_file to get current content and ensure old_string matches exactly (whitespace, tabs, newlines).`;
82
+ }
33
83
  function showDiff(filePath, oldContent, newContent) {
34
84
  const relativePath = path.relative(process.cwd(), filePath);
35
85
  console.log(chalk.blue.bold(`\n📝 Edit ${relativePath}:`));
@@ -125,11 +175,28 @@ export const tools = [
125
175
  }
126
176
  }
127
177
  },
178
+ {
179
+ type: 'function',
180
+ function: {
181
+ name: 'search_replace',
182
+ description: 'Replaces old_string with new_string in a file. PREFERRED for edits and modifications: targeted, minimal changes. Use read_file first to get current content. For new files or complete rewrites use write_file. expected_replacements (optional): if set, fails when count of matches ≠ value (prevents unintended broad changes).',
183
+ parameters: {
184
+ type: 'object',
185
+ properties: {
186
+ path: { type: 'string', description: 'The path to the file' },
187
+ old_string: { type: 'string', description: 'Exact text to find and replace (must match file content including whitespace)' },
188
+ new_string: { type: 'string', description: 'Replacement text' },
189
+ expected_replacements: { type: 'number', description: 'Optional: fail if number of occurrences ≠ this (safety guard)' }
190
+ },
191
+ required: ['path', 'old_string', 'new_string']
192
+ }
193
+ }
194
+ },
128
195
  {
129
196
  type: 'function',
130
197
  function: {
131
198
  name: 'write_file',
132
- description: 'Writes content to a file. Overwrites if exists, creates if not.',
199
+ description: 'Writes full content to a file. Overwrites if exists, creates if not. Use for new files or complete rewrites. For small edits, prefer search_replace. When modifying existing work from this chat, use the same path as before (see user message [Pokt] hint or prior tool calls); call read_file first if you need the current contents.',
133
200
  parameters: {
134
201
  type: 'object',
135
202
  properties: {
@@ -188,6 +255,34 @@ export async function executeTool(name, argsStr) {
188
255
  if (name === 'read_file') {
189
256
  return fs.readFileSync(path.resolve(process.cwd(), args.path), 'utf8');
190
257
  }
258
+ if (name === 'search_replace') {
259
+ const filePath = path.resolve(process.cwd(), args.path);
260
+ if (!fs.existsSync(filePath)) {
261
+ return `Error: File not found: ${args.path}. Use write_file to create it.`;
262
+ }
263
+ const content = fs.readFileSync(filePath, 'utf8');
264
+ const oldStr = args.old_string ?? '';
265
+ const newStr = args.new_string ?? '';
266
+ if (oldStr === newStr) {
267
+ return `search_replace: old_string and new_string are identical; no change made.`;
268
+ }
269
+ const expected = typeof args.expected_replacements === 'number' ? args.expected_replacements : undefined;
270
+ const occurrences = content.split(oldStr).length - 1;
271
+ if (occurrences === 0) {
272
+ const errMsg = findClosestMatchAndBuildError(content, oldStr, args.path);
273
+ return errMsg;
274
+ }
275
+ if (expected !== undefined && occurrences !== expected) {
276
+ return `search_replace failed: found ${occurrences} occurrence(s) of old_string, but expected_replacements=${expected}. Adjust old_string to be unique or set expected_replacements to ${occurrences}.`;
277
+ }
278
+ const newContent = content.split(oldStr).join(newStr);
279
+ fs.writeFileSync(filePath, newContent, 'utf8');
280
+ const rel = path.relative(process.cwd(), filePath);
281
+ if (!isGeneratedNoisePath(rel) || !looksLikeMcpJsonDump(newContent)) {
282
+ showDiff(filePath, content, newContent);
283
+ }
284
+ return `Successfully applied search_replace to ${args.path} (${occurrences} replacement(s)).`;
285
+ }
191
286
  if (name === 'write_file') {
192
287
  const filePath = path.resolve(process.cwd(), args.path);
193
288
  const oldContent = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pokt-cli",
3
- "version": "1.0.10",
3
+ "version": "1.0.11",
4
4
  "description": "Vibe Coding AI CLI for OpenRouter and Ollama",
5
5
  "main": "./dist/bin/pokt.js",
6
6
  "type": "module",