-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathserver.js
More file actions
5338 lines (5007 loc) · 209 KB
/
Copy pathserver.js
File metadata and controls
5338 lines (5007 loc) · 209 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
'use strict';
// Minimal zero-dependency static server for a VEIL digital twin.
// Serves ./public (viewer) and ./data (bundled geospatial data). No database,
// no cloud, no build step. POST /api/chat additionally proxies the viewer's
// chat panel to OpenAI with the twin MCP server's tools (see "chat API"
// below) — still no npm dependencies.
const http = require('http');
const crypto = require('crypto');
const fs = require('fs');
const fsp = fs.promises;
const os = require('os');
const path = require('path');
const { URL } = require('url');
const { spawn, spawnSync } = require('child_process');
const ROOT = __dirname;
// A twin's data dir. Defaults to ./data; set TWIN_DATA_DIR to serve an
// alternate/scratch twin from the same checkout (its /data/* requests are
// served from there, /public is unchanged) without touching ./data.
const DATA_DIR = path.resolve(ROOT, process.env.TWIN_DATA_DIR || 'data');
const PORT = Number(process.env.PORT) || 4173;
const HOST = process.env.HOST || '127.0.0.1';
// Hosted mode keeps the local-first defaults intact, but lets one public Node
// process issue anonymous session cookies and provision an isolated data dir for
// each visitor. A template may be supplied, but hosted product deployments can
// also start from an empty data dir and let the visitor build a twin via /init.
const HOSTED_MODE = process.env.VEIL_HOSTED === '1';
const HOSTED_ROOT = path.resolve(ROOT, process.env.VEIL_HOSTED_ROOT || 'hosted');
const HOSTED_TEMPLATE_DATA_DIR = process.env.VEIL_HOSTED_TEMPLATE_DATA_DIR
? path.resolve(ROOT, process.env.VEIL_HOSTED_TEMPLATE_DATA_DIR)
: null;
const HOSTED_COOKIE = 'veil_session';
const HOSTED_TWIN_ID = 'default';
const HOSTED_SECRET = process.env.VEIL_SESSION_SECRET
|| (HOSTED_MODE ? crypto.randomBytes(32).toString('hex') : 'local-dev-secret');
if (HOSTED_MODE && !process.env.VEIL_SESSION_SECRET) {
console.warn('VEIL_HOSTED=1 without VEIL_SESSION_SECRET: hosted sessions will be invalidated on restart.');
}
// ---------------------------------------------------------------- chat API
// POST /api/chat lets the viewer's chat panel ask an LLM about the land.
// The LLM's tools ARE the twin MCP server: we spawn scripts/mcp_server.py
// once, speak JSON-RPC to it over stdio, and hand its tool catalog to
// OpenAI's function calling. Still zero npm dependencies (built-in fetch +
// child_process).
// Provider: 'openai' (hosted Responses API, default) or 'ollama' (a local model
// over Ollama's native /api/chat). CHAT_PROVIDER picks it; if unset but
// OLLAMA_MODEL is given, we infer 'ollama'. Ollama needs no key and nothing
// leaves the machine.
const CHAT_PROVIDER = (process.env.CHAT_PROVIDER
|| (process.env.OLLAMA_MODEL ? 'ollama' : 'openai')).toLowerCase();
const OPENAI_MODEL = process.env.OPENAI_MODEL || 'gpt-5.5';
const OPENAI_REASONING = process.env.OPENAI_REASONING_EFFORT || 'low';
// When set, the server never spends its own key: every /api/chat request must
// carry the caller's key (X-OpenAI-Key). Use this for any public deployment so
// strangers reaching the port bring their own quota, not yours.
const OPENAI_REQUIRE_USER_KEY = process.env.OPENAI_REQUIRE_USER_KEY === '1';
const OLLAMA_HOST = (process.env.OLLAMA_HOST || 'http://127.0.0.1:11434').replace(/\/+$/, '');
const OLLAMA_MODEL = process.env.OLLAMA_MODEL || 'gpt-oss:20b';
// Context window for the local model. gpt-oss:20b's KV cache is cheap, so a
// large window fits comfortably on a 24 GB card and keeps a long tool session
// from truncating; set OLLAMA_MODEL / OLLAMA_NUM_CTX explicitly to override.
const OLLAMA_NUM_CTX = Number(process.env.OLLAMA_NUM_CTX) || 98304;
// Sampling temperature for the local model. 0 keeps agentic tool use deterministic
// and avoids truncated/malformed tool-call JSON or empty-answer turns; raise only
// if you want more varied prose.
const OLLAMA_TEMPERATURE = process.env.OLLAMA_TEMPERATURE !== undefined
? Number(process.env.OLLAMA_TEMPERATURE) : 0;
// The active chat model label (shown in the panel / echoed in responses).
const CHAT_MODEL = CHAT_PROVIDER === 'ollama' ? OLLAMA_MODEL : OPENAI_MODEL;
// GPT reasoning models may choose one function per response even when parallel
// calls are available. Keep the loop bounded, but leave enough room for a Plan
// request to discover its plan + target feature and create one review proposal.
const MAX_TOOL_ROUNDS = Math.max(1, Math.min(64,
Math.floor(Number(process.env.OPENAI_MAX_TOOL_ROUNDS) || 16)));
const OPENAI_NEAR_TOOL_CAP_WARNING = 3;
// Local reasoning models often emit ONE tool call per turn after thinking, so they
// need many more rounds to work through a multi-step question. A
// site-selection question (gather facts at 3 spots + draw 3 points) can spend
// ~16-20 single-call turns, so the budget has to clear that or the model gets cut
// off before it ever writes its answer.
const MAX_TOOL_ROUNDS_OLLAMA = Number(process.env.OLLAMA_MAX_TOOL_ROUNDS) || 24;
const MAX_PARSE_NUDGES = 4;
const OLLAMA_NEAR_TOOL_CAP_WARNING = 3;
const TOOL_RESULT_CAP = 60000; // chars per tool result sent to the model
function openaiKey() {
if (process.env.OPENAI_API_KEY) return process.env.OPENAI_API_KEY.trim();
try {
return fs.readFileSync(path.join(ROOT, '.openai_key'), 'utf8').trim();
} catch (_err) {
return null;
}
}
// -- minimal MCP stdio client (one persistent python child per twin) -------
const mcpClients = new Map(); // dataDir -> { proc, pending, nextId, tools, init }
// The chat MCP server and hydrology simulation need the geospatial stack
// (pyproj/GDAL/numpy). A bare `python3` — especially under a GUI-launched login
// profile that starts the server — can resolve to an interpreter without it,
// so tools or scenarios fail with "No module named ...". Resolve a Python that
// has the stack: an explicit VEIL_MCP_PYTHON wins for MCP, else the project's
// dedicated .venv-mcp, else python3. Hydrology can be overridden separately with
// VEIL_HYDRO_PYTHON but otherwise uses the same stack.
function resolveMcpPython() {
const explicit = (process.env.VEIL_MCP_PYTHON || '').trim();
if (explicit) return explicit;
const venv = path.join(ROOT, '.venv-mcp', 'bin', 'python');
try {
fs.accessSync(venv, fs.constants.X_OK);
return venv;
} catch (_err) { /* fall through */ }
return 'python3';
}
const MCP_PYTHON = resolveMcpPython();
const HYDRO_PYTHON = (process.env.VEIL_HYDRO_PYTHON || '').trim() || MCP_PYTHON;
const FIRE_PYTHON = (process.env.VEIL_FIRE_PYTHON || '').trim() || HYDRO_PYTHON;
function mcpSpawn(dataDir = DATA_DIR) {
const proc = spawn(MCP_PYTHON, [path.join(ROOT, 'scripts', 'mcp_server.py')], {
env: { ...process.env, TWIN_DATA_DIR: dataDir },
cwd: ROOT,
stdio: ['pipe', 'pipe', 'inherit'],
});
const state = { proc, pending: new Map(), nextId: 1, tools: null, buf: '', dataDir };
proc.stdout.setEncoding('utf8');
proc.stdout.on('data', (chunk) => {
state.buf += chunk;
let nl;
while ((nl = state.buf.indexOf('\n')) >= 0) {
const line = state.buf.slice(0, nl).trim();
state.buf = state.buf.slice(nl + 1);
if (!line) continue;
let msg;
try { msg = JSON.parse(line); } catch (_err) { continue; }
const waiter = state.pending.get(msg.id);
if (!waiter) continue;
state.pending.delete(msg.id);
if (msg.error) waiter.reject(new Error(msg.error.message || 'MCP error'));
else waiter.resolve(msg.result);
}
});
proc.on('close', () => {
state.pending.forEach((w) => w.reject(new Error('MCP server exited')));
state.pending.clear();
if (mcpClients.get(dataDir) === state) mcpClients.delete(dataDir); // respawn lazily
});
proc.on('error', (err) => {
// spawn failure (e.g. a bad/missing interpreter) or a runtime process
// error arrives as an async 'error' event the request try/catch can't see;
// fail pending waiters and drop this instance instead of letting it become
// an uncaughtException that takes down the whole static server.
state.pending.forEach((w) => w.reject(err instanceof Error ? err : new Error(String(err))));
state.pending.clear();
if (mcpClients.get(dataDir) === state) mcpClients.delete(dataDir);
});
// A write to a dead child's stdin emits EPIPE on the writable stream; swallow
// it so it never crashes the process (waiters are already failed above).
proc.stdin.on('error', () => {});
const writeLine = (obj) => {
try {
proc.stdin.write(JSON.stringify(obj) + '\n');
return true;
} catch (_err) {
return false;
}
};
state.request = (method, params) => new Promise((resolve, reject) => {
const id = state.nextId++;
state.pending.set(id, { resolve, reject });
if (!writeLine({ jsonrpc: '2.0', id, method, params })) {
state.pending.delete(id);
reject(new Error('MCP server unavailable'));
return;
}
setTimeout(() => {
if (state.pending.delete(id)) reject(new Error(`MCP ${method} timed out`));
}, 120000);
});
state.notify = (method, params) => {
writeLine({ jsonrpc: '2.0', method, params });
};
state.init = (async () => {
await state.request('initialize', {
protocolVersion: '2025-06-18',
capabilities: {},
clientInfo: { name: 'veil-chat', version: '1.0' },
});
state.notify('notifications/initialized', {});
const listed = await state.request('tools/list', {});
state.tools = listed.tools || [];
})();
return state;
}
async function mcpReady() {
return mcpReadyFor(DATA_DIR);
}
async function mcpReadyFor(dataDir = DATA_DIR) {
let client = mcpClients.get(dataDir);
if (!client) {
client = mcpSpawn(dataDir);
mcpClients.set(dataDir, client);
}
await client.init;
return client;
}
async function mcpCall(name, args, dataDir = DATA_DIR) {
const client = await mcpReadyFor(dataDir);
const result = await client.request('tools/call', { name, arguments: args || {} });
const text = (result.content || [])
.filter((c) => c.type === 'text')
.map((c) => c.text)
.join('\n');
return text || JSON.stringify(result);
}
// -- scope context: what the chat panel selected in the 3D scene ----------
// Keep this as coordinate context only. The model should first decide what
// evidence the question needs, then call identify/summarize/layer tools itself.
async function scopeContext(scope) {
if (!scope || scope.type === 'all' || !scope.type) {
return 'Scope: the whole twin. Use tools as needed; describe_place gives lightweight location and coordinate context.';
}
if (scope.type === 'region') {
const region = { polygon: scope.polygon };
return [
'Scope: a region the user drew in the 3D viewer.',
`Region object for spatial tools (scene-local meters): ${JSON.stringify(region)}`,
'When the user says "here"/"this area", they mean this region. Pass this exact',
'region object to find_entities / aggregate_entities / canopy_change / summarize_region.',
].join('\n');
}
if (scope.type === 'point') {
const radius = Number(scope.radius_m) || 100;
const point = scope.point;
const region = { within_m: radius, point };
return [
'Scope: a single point the user picked in the 3D viewer.',
`Point (scene-local meters): ${JSON.stringify(point)}`,
`Region object for spatial tools (${radius} m around it): ${JSON.stringify(region)}`,
'When the user says "here"/"this spot", they mean this point and its surroundings.',
].join('\n');
}
throw new Error(`unknown scope type: ${scope.type}`);
}
function cap(text, n = TOOL_RESULT_CAP) {
return text.length > n ? `${text.slice(0, n)}\n…[truncated ${text.length - n} chars]` : text;
}
// Echo a bounded, structured view of a tool result into the returned trace so the
// benchmark evaluator can credit data the twin actually surfaced (not just what the
// model retyped). Parse JSON when it's small enough to carry safely; otherwise drop
// to a truncated marker so a huge payload can never bloat the chat response.
// Large enough that real tool payloads (identify_at pretty-prints to ~14 KB,
// describe_twin larger) are echoed whole so the evaluator can read their layer
// ids / facts; the marker only guards against a pathological multi-hundred-KB
// result bloating the response. This is the RETURNED trace, separate from the
// smaller TOOL_RESULT_CAP slice fed back to the model.
const TRACE_RESULT_CAP = 200000; // chars of tool result echoed into the returned trace
function traceResult(result) {
const text = typeof result === 'string' ? result : String(result);
if (text.length <= TRACE_RESULT_CAP) {
try { return JSON.parse(text); } catch (_err) { return text; }
}
return { truncated: true, chars: text.length, preview: text.slice(0, 800) };
}
const JSON_FINALIZE_PROMPT = [
'Using only facts already in this conversation, output EXACTLY ONE valid JSON object and',
'nothing else. If you do not have a value, omit that key rather than invent it.',
'Use concise machine-checkable claim keys and real units. Do not include markdown,',
'code fences, or explanatory prose.',
].join(' ');
function hasContractJson(text) {
return extractContractJsonCandidates(text) !== null;
}
function extractContractJsonCandidates(text) {
const candidates = [];
const raw = String(text || '');
const blockMatches = raw.match(/```(?:json)?[\s\S]*?```/gi) || [];
for (const block of blockMatches) {
candidates.push(block.replace(/^```(?:json)?\s*/i, '').replace(/```$/, '').trim());
}
candidates.push(...scanBalancedJsonCandidates(raw));
for (let i = candidates.length - 1; i >= 0; i -= 1) {
const candidate = candidates[i];
try {
const parsed = JSON.parse(candidate);
if (
parsed && typeof parsed === 'object' && !Array.isArray(parsed)
&& Object.prototype.hasOwnProperty.call(parsed, 'answer')
&& Object.prototype.hasOwnProperty.call(parsed, 'claims')
) {
return parsed;
}
} catch (_err) {
// keep scanning
}
}
return null;
}
function looksLikeJsonRequest(text) {
return /\bjson\b/i.test(String(text || ''));
}
function scanBalancedJsonCandidates(text) {
const raw = String(text || '');
const out = [];
let inString = false;
let stringQuote = '';
let escaped = false;
let depth = 0;
let start = -1;
for (let i = 0; i < raw.length; i += 1) {
const ch = raw[i];
if (inString) {
if (escaped) {
escaped = false;
} else if (ch === '\\') {
escaped = true;
} else if (ch === stringQuote) {
inString = false;
stringQuote = '';
}
continue;
}
if (ch === '"' || ch === '\'') {
inString = true;
stringQuote = ch;
continue;
}
if (ch === '{') {
if (depth === 0) start = i;
depth += 1;
continue;
}
if (ch === '}' && depth > 0) {
depth -= 1;
if (depth === 0 && start >= 0) {
out.push(raw.slice(start, i + 1));
start = -1;
}
}
}
return out;
}
function openaiOutputToText(output) {
return (output || [])
.filter((o) => o.type === 'message')
.flatMap((o) => o.content || [])
.filter((c) => c.type === 'output_text')
.map((c) => c.text || '')
.join('\n');
}
function drawPointCoordinateKey(point) {
if (!point || typeof point !== 'object') return null;
const x = Number.isFinite(Number(point.x)) ? Number(point.x)
: Number.isFinite(Number(point.lon)) ? Number(point.lon)
: Number.isFinite(Number(point.lng)) ? Number(point.lng)
: Number.NaN;
const y = Number.isFinite(Number(point.y)) ? Number(point.y)
: Number.isFinite(Number(point.lat)) ? Number(point.lat)
: Number.NaN;
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
return `${x.toFixed(6)}|${y.toFixed(6)}`;
}
function drawPointResultFlags(result) {
const lower = String(result || '').toLowerCase();
return {
outside: /\boutside\b.*\b(aoi|boundary|parcel|property)\b/.test(lower),
inside: /\binside\b.*\b(aoi|boundary|parcel|property)\b/.test(lower),
};
}
function shouldAskForPointPlacement(userText) {
const text = `${String(userText || '')}`.toLowerCase();
return /\b(draw|place|mark|point|recommend|site|recommendation)\b/.test(text);
}
function pointPlacementHint({ userText, drawPoints, outsideCount }) {
if (!shouldAskForPointPlacement(userText)) return null;
if (!drawPoints.size && !/point|recommend|site|place|draw/.test(String(userText || '').toLowerCase())) return null;
if (outsideCount > 0) return {
message: 'Some points appear outside parcel scope. Use only coordinates from tool results that are inside the property before finalizing.',
};
return {
message: 'For placement questions, keep draw_point coordinates distinct and in-property, and avoid reusing any coordinate.',
};
}
function isEcologyIntent(text) {
return /\b(ecology|ecological|habitat|species|wildlife|animal|animals|hunting|hunt|deer|turkey|bear|bird|birds|mammal|reptile|amphibian|fish|pollinator|wetland|wetlands|forest|forests|vegetation|plant|plants|invasive|native|conservation|biodiversity|land\s*cover|soil|soils|geology|natural[-\s]?resource)\b/i
.test(String(text || ''));
}
function isPlanEditIntent(text) {
const value = String(text || '');
const mutation = /\b(add|apply|build|clear|cut|delete|dig|fill|grade|lower|modify|move|plant|raise|remove|replace|restore)\b/i.test(value)
|| /\b(propose|preview)\b/i.test(value);
const land = /\b(plan|terrain|earth|soil|tree|trees|shrub|shrubs|vegetation|creek|stream|swale|orchard|garden|pond|berm)\b/i.test(value);
return mutation && land;
}
function isEcologyLayerInspectionTool(name) {
return new Set([
'list_layers',
'layer_summary',
'identify_at',
'sample_raster',
'summarize_region',
'filter_layer',
'set_layer_visibility',
]).has(name);
}
function needsThematicLayerPreflight(name) {
return new Set([
'recommend_sites',
'draw_point',
'draw_polygon',
'filter_layer',
'set_layer_visibility',
]).has(name);
}
const ECOLOGY_PREFLIGHT_NUDGE = [
'This request depends on thematic/geospatial evidence. First state what spatial',
'evidence would ideally answer it, then inspect list_layers to see what this',
'twin actually has. Layer ids may be unexpected; choose from available labels,',
'descriptions, themes, fields, legends, and provenance. Use layer_summary on',
'promising candidates before recommending, revealing layers, or drawing sites.',
].join(' ');
function ecologyPreflightToolResult() {
return JSON.stringify({
error: 'thematic_layer_preflight_required',
message: ECOLOGY_PREFLIGHT_NUDGE,
next_steps: [
'Use list_layers to inspect the available catalog, including text_metadata descriptions.',
'Use layer_summary for promising candidate layers, not just expected layer ids.',
'Name missing evidence and any proxy layers before making recommendations.',
'Call recommend_sites, filter_layer, or draw_point only after that preflight.',
],
});
}
function ecologyDynamicInstructions(userText) {
if (!isEcologyIntent(userText) || isPlanEditIntent(userText)) return '';
return [
'',
'CURRENT REQUEST THEMATIC PREFLIGHT',
'- The latest user request appears to depend on thematic/geospatial evidence',
' such as ecology, wildlife, habitat, vegetation, land cover, soils, geology,',
' wetlands, hydrology, hazards, access, or conservation.',
'- First decide what evidence would ideally answer the question. Then inspect',
' list_layers to see what is actually available; use descriptions/metadata,',
' labels, themes, fields, legends, and provenance rather than expecting exact',
' layer ids.',
'- Use layer_summary on promising layers, state missing evidence or proxy',
' choices, then filter/reveal layers, recommend sites, or draw points.',
].join('\n');
}
function planEditDynamicInstructions(userText) {
if (!isPlanEditIntent(userText)) return '';
return [
'',
'CURRENT REQUEST IS A PLAN EDIT',
'- Use the Plan proposal workflow directly. Do not run thematic layer',
' discovery, reveal atlas layers, draw point markers, or call a separate',
' visualization tool; propose_plan_edits demonstrates its preview itself.',
'- Reuse facts already present in this conversation. Gather only the current',
' plan/revision and the mapped target geometry actually needed for the edit.',
'- For vegetation removal near a stream/road/other mapped feature, do NOT',
' enumerate trees or copy its geometry. Find the target entity, then call',
' propose_vegetation_clearance once with its ID, buffer_m, and tree/shrub',
' kinds. The tool obtains the geometry and freezes the matching entity IDs.',
'- If target discovery returns multiple plausible linear features and the user',
' did not identify one by name/location, do not silently choose the first ID;',
' inspect the candidates or ask which feature they mean.',
'- After any propose_* tool succeeds, stop calling tools. Briefly report the',
' preview quantities and ask the user to review/confirm. Never apply in the',
' same turn that creates the proposal.',
].join('\n');
}
function isPlanConfirmationIntent(text) {
let value = String(text || '').trim().toLowerCase();
if (!value || /\b(do not|don't|dont|not yet|wait|hold|cancel|stop)\b/.test(value)) {
return false;
}
value = value.replace(/[^a-z0-9_\s-]+/g, ' ').replace(/\s+/g, ' ').trim();
value = value.replace(/^please\s+/, '').replace(/\s+please$/, '');
value = value.replace(/\bproposal_[a-z0-9]+\b/g, 'the proposal');
return /^(?:yes\s+)?(?:yes|apply(?:\s+(?:it|this|that|the proposal|the changes))?|confirm(?:\s+(?:it|this|that|the proposal|the changes))?|confirm and apply|go ahead(?:\s+and\s+(?:apply(?:\s+it)?|make the changes))?|do it|make (?:the|these|those) changes|accept(?:\s+(?:it|this|that|the proposal))?|approve(?:\s+(?:it|this|that|the proposal))?|looks good(?:\s+apply it)?)$/.test(value);
}
function loadPlanProposal(proposalId, dataDir = DATA_DIR) {
if (!/^proposal_[a-z0-9]+$/.test(String(proposalId || ''))) return null;
try {
const file = path.join(dataDir, 'plans', 'proposals', `${proposalId}.json`);
const proposal = JSON.parse(fs.readFileSync(file, 'utf8'));
return proposal && typeof proposal === 'object' ? proposal : null;
} catch (_err) {
return null;
}
}
function planConfirmationContext(userText, history, options = {}) {
if (!isPlanConfirmationIntent(userText)) return null;
const dataDir = options.dataDir || DATA_DIR;
let annotations = options.annotations;
if (annotations === undefined) {
try {
annotations = JSON.parse(fs.readFileSync(path.join(dataDir, 'annotations.json'), 'utf8'));
} catch (_err) {
annotations = null;
}
}
const candidates = [];
const explicit = String(userText || '').match(/\bproposal_[a-z0-9]+\b/gi) || [];
candidates.push(...explicit.map((value) => value.toLowerCase()));
const activeId = annotations?.plan_view?.proposal_id;
if (activeId) candidates.push(String(activeId));
for (let index = (history || []).length - 1; index >= 0; index -= 1) {
const ids = String(history[index]?.content || '').match(/\bproposal_[a-z0-9]+\b/gi) || [];
candidates.push(...ids.reverse().map((value) => value.toLowerCase()));
}
const loader = options.loadProposal || ((proposalId) => loadPlanProposal(proposalId, dataDir));
for (const proposalId of [...new Set(candidates)]) {
const proposal = loader(proposalId);
if (!proposal || !['proposed', 'applied'].includes(proposal.status)) continue;
return {
proposal_id: proposal.proposal_id,
status: proposal.status,
applied_revision_id: proposal.applied_revision_id || null,
plan_id: proposal.plan_id,
expected_revision_id: proposal.expected_revision_id,
label: proposal.label || 'Plan proposal',
preview: proposal.preview || {},
};
}
return null;
}
function appliedPlanReply(context, result) {
const revisionId = result?.revision?.revision_id;
const removed = context?.preview?.vegetation?.entities_removed;
const parts = [`Applied **${context?.label || 'the Plan proposal'}**.`];
if (Number.isFinite(Number(removed))) {
parts.push(`The **${Number(removed).toLocaleString('en-US')}** previewed vegetation removals are now committed.`);
}
if (revisionId) parts.push(`New revision: **${revisionId}**.`);
return parts.join(' ');
}
const CHAT_SYSTEM_PROMPT = [
'You are the resident guide of a VEIL digital twin — a georeferenced 3D model of',
'a real place with terrain, vegetation, buildings, soils, hydrology, land cover',
'and habitat data. You answer questions about THIS land using the read-only twin',
'tools, and you show places on the user\'s live 3D map.',
'',
'GROUNDING',
'- Start by considering the nature of the user question and what spatial',
' evidence would ideally answer it. Do this before inspecting the layer',
' inventory. If you need location/coordinate context, call describe_place;',
' use describe_twin only when broader run history or inventory counts matter.',
'- Every figure must come from a tool result — never invent or estimate numbers.',
' Keep each number\'s real unit (count, m, m², ha, acres, %); do not relabel a',
' percentage as an area or reuse one figure for unrelated things. If a tool did',
' not give you something, say so plainly instead of guessing.',
'- Prefer aggregate_entities and summarize_region for counts and statistics; use',
' small limit values on find_entities. For water/runoff questions use the',
' hydrology tools (hydrology_at, hydrology_summary, run_scenario). Coordinates:',
' tools take {lat,lon} degrees or scene-local meters {x,y} (results echo both);',
' distances and heights are meters.',
'',
'QUESTION-FIRST LAYER DISCOVERY',
'- For thematic, suitability, hazard, habitat, wetland, land-cover, soil,',
' geology, hydrology, access, or conservation questions, first identify the',
' ideal/helpful spatial evidence. Then call list_layers to inspect what this',
' twin actually has. Layer ids and names may be unfamiliar or incomplete;',
' choose from available descriptions/text_metadata, labels, themes, fields,',
' legend previews, provenance, and query/filter/drape flags.',
'- After list_layers, call layer_summary for the promising candidate layers to',
' inspect labels, fields, legends, filterable values, and natural-language',
' metadata. Do not assume an expected layer id exists.',
'- For species questions, look for any species/habitat/range layers in the',
' catalog. If GAP/species-habitat is present, use layer_summary or identify_at',
' results to find the exact species common name before filtering.',
'- If a relevant layer is absent or empty, say that plainly and name what was',
' checked. If using a proxy layer, explain briefly why it is only a proxy.',
'',
'SHOW PLACES ON THE MAP — this is a hard rule, not optional:',
'If the user asks for JSON, your FINAL message must be valid JSON only — no prose,',
' no markdown, and no fenced blocks.',
'- STAY ON THE PROPERTY: every marker MUST fall inside the property boundary — the',
' parcel AOI. Scope the searches you draw from to region {"aoi": true} so you',
' anchor markers to features within the property, never the surrounding apron/area.',
' Only draw a point outside the parcel if the user EXPLICITLY asks to expand the',
' scope to the surrounding area.',
'- Whenever your answer points at one or more specific places, you MUST call',
' draw_point (a spot) for EACH place, with a short label. Prefer draw_point',
' for exact spots; prefer filter_layer for mapped classes, habitat extents,',
' or any answer about where a condition/species/class is present.',
'- Use REAL coordinates from a tool result (an entity\'s `position` or a feature\'s',
' centroid) — never invented numbers. When a place is a relevant feature (water,',
' an edge, a road), anchor the marker to that feature\'s coordinates.',
'- Never write "I\'ll draw…", "I\'ll mark…", "let me plot…" or similar. Drawing is',
' a tool call you actually make, not a sentence you say. If you mentioned a place',
' but did not call a draw tool for it, you are not done.',
'- Draw 2-3 places at most, each at a DIFFERENT location, each exactly once. Never',
' draw the same coordinate twice. Each marker must use a real coordinate from a',
' tool result and stay inside the property. Do NOT call clear_drawings (the user',
' clears the',
' map) and do not redraw or second-guess a marker you already placed.',
'- Don\'t recite raw coordinates in prose — the marker shows the location. Just',
' name what you drew, then give your final written answer.',
'',
'REVEAL RELEVANT MAP LAYERS',
'- When a layer directly supports your answer, show it on the map after you',
' have inspected the catalog/summary. Prefer',
' filter_layer over set_layer_visibility so the map reveals only the relevant',
' class, species, soil unit, geology type, wetland type, land-cover class, or',
' habitat cells.',
'- For species questions, call filter_layer("gap_species_richness", [exact',
' species common name]) when that species is available. This is the preferred',
' way to show modeled habitat/range on the terrain.',
'- For categorical raster layers, filter by legend class names from',
' layer_summary. For vector layers, filter by the relevant label or field',
' value from layer_summary.',
'- Use draw_point only for specific recommended spots or sampled evidence',
' locations; use filter_layer when the answer is about an area, class, or',
' habitat extent.',
'',
'BE EFFICIENT — you have a limited number of tool turns:',
'- Gather only the data you actually need, then commit to an answer. Do not repeat',
' a query you already ran or keep re-checking the same thing.',
'- The normal arc is: a few read calls → one draw call per place → your final',
' written reply. End with the reply; don\'t keep calling tools after you can answer.',
'',
'ANSWER STYLE — the chat panel is small and renders ONLY **bold**, "- " bullet',
'lines, and short paragraphs:',
'- Do NOT use markdown tables, headings (#), or code blocks — they show up as raw',
' symbols. Use a one- or two-sentence lead answer, then at most a few "- "',
' bullets for the key facts, with **bold** on the essentials.',
'- Be concise and conversational. Do not narrate your tool calls or add a "how I',
' got the numbers" / methodology section. Name a data source (LiDAR, gSSURGO,',
' LANDFIRE, GAP…) only in a few words when it genuinely matters.',
].join('\n');
// GPT-5.5 function calling lives on the Responses API (chat/completions
// rejects tools+reasoning for it). Tool rounds chain via previous_response_id
// so reasoning state carries across calls.
async function openaiResponses(payload, apiKey, signal = null) {
const res = await fetch('https://api.openai.com/v1/responses', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify(payload),
...(signal ? { signal } : {}),
});
if (!res.ok) {
const detail = await res.text();
throw new Error(`OpenAI ${res.status}: ${detail.slice(0, 400)}`);
}
return res.json();
}
// Ollama's native /api/chat speaks the same tool/function-calling schema and,
// unlike its OpenAI-compatible endpoint, honors options.num_ctx — which we need
// to size the context window so the model fits the GPU. No auth, no network
// egress (the local daemon). Tool rounds carry state by replaying the growing
// message list (there is no previous_response_id here).
async function ollamaChat(payload, signal = null) {
let res;
try {
res = await fetch(`${OLLAMA_HOST}/api/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
...(signal ? { signal } : {}),
});
} catch (err) {
if (signal && signal.aborted) throw err; // client disconnected — propagate cleanly
throw new Error(`cannot reach Ollama at ${OLLAMA_HOST} — is "ollama serve" running? (${err.message || err})`);
}
if (!res.ok) {
const detail = await res.text();
throw new Error(`Ollama ${res.status}: ${detail.slice(0, 400)}`);
}
return res.json();
}
// --- provider runners: each takes the shared {history, toolDefs, instructions}
// and drives the tool loop in its provider's dialect, returning {reply, trace}.
function collectLayerRefs(value, out = new Map(), depth = 0) {
if (!value || depth > 5 || out.size >= 12) return out;
if (typeof value === 'string') {
const s = value.trim();
if (s && /^[a-z0-9][a-z0-9_.:-]{2,}$/i.test(s) && /layer|soil|land|geo|wetland|hydro|trail|habitat|cover|forest|vegetation|evt|nwi|ssurgo|gap/i.test(s)) {
out.set(s, s);
}
return out;
}
if (Array.isArray(value)) {
for (const item of value) collectLayerRefs(item, out, depth + 1);
return out;
}
if (typeof value !== 'object') return out;
const id = value.layer_id || value.layerId || value.layer;
const label = value.layer_label || value.label || value.name;
if (typeof id === 'string' && id.trim()) {
out.set(id.trim(), typeof label === 'string' && label.trim() ? `${id.trim()} — ${label.trim()}` : id.trim());
}
for (const [key, child] of Object.entries(value)) {
if (/source_path|store_path|path|geometry|coordinates|features/i.test(key)) continue;
collectLayerRefs(child, out, depth + 1);
if (out.size >= 12) break;
}
return out;
}
function layerRefsFromToolActivity(args, result) {
const out = collectLayerRefs(args);
const text = typeof result === 'string' ? result : JSON.stringify(result || '');
if (text && text.length <= TRACE_RESULT_CAP) {
try { collectLayerRefs(JSON.parse(text), out); } catch (_err) { /* plain text result */ }
}
return Array.from(out.values()).slice(0, 8);
}
const PLAN_PROPOSAL_TOOLS = new Set([
'propose_plan_edits', 'propose_vegetation_clearance',
'propose_swale', 'propose_orchard', 'propose_garden',
]);
const PLAN_TERMINAL_TOOLS = new Set([...PLAN_PROPOSAL_TOOLS, 'apply_plan_proposal']);
const PLAN_TERMINAL_FINALIZE_PROMPT = [
'The Plan tool just succeeded. Do not call another tool in this turn.',
'If this was a proposal, report its preview quantities and ask the user to',
'review/confirm it; do not apply it yet. If it was an apply, report completion.',
].join(' ');
const TOOL_BUDGET_FINALIZE_PROMPT = [
'The tool budget is exhausted. Do not call more tools. Give the user a concise',
'status that says exactly what completed and what remains. Never claim that a',
'proposal, edit, drawing, or analysis happened unless a tool result confirmed it.',
].join(' ');
function successfulPlanTerminalTool(name, result) {
if (!PLAN_TERMINAL_TOOLS.has(name)) return false;
let parsed;
try { parsed = JSON.parse(String(result || '')); } catch (_err) { return false; }
if (!parsed || typeof parsed !== 'object' || parsed.error) return false;
if (name === 'apply_plan_proposal') {
return !!(parsed.revision && parsed.proposal?.status === 'applied');
}
return typeof parsed.proposal_id === 'string' && parsed.proposal_id.startsWith('proposal_');
}
function toolResultForModel(name, result) {
if (!PLAN_TERMINAL_TOOLS.has(name)) return cap(String(result || ''));
let parsed;
try { parsed = JSON.parse(String(result || '')); } catch (_err) {
return cap(String(result || ''));
}
if (!parsed || typeof parsed !== 'object' || parsed.error) {
return cap(String(result || ''));
}
const compactVisualization = parsed.visualization && {
plan_id: parsed.visualization.plan_id,
revision_id: parsed.visualization.revision_id,
proposal_id: parsed.visualization.proposal_id,
label: parsed.visualization.label,
view: parsed.visualization.view,
};
if (name === 'apply_plan_proposal') {
return JSON.stringify({
proposal: parsed.proposal,
plan: parsed.plan && {
plan_id: parsed.plan.plan_id, name: parsed.plan.name,
head_revision_id: parsed.plan.head_revision_id,
},
revision: parsed.revision && {
revision_id: parsed.revision.revision_id,
parent_revision_id: parsed.revision.parent_revision_id,
message: parsed.revision.message,
},
diff: parsed.materialized?.diff,
visualization: compactVisualization,
});
}
const proposedEdits = (parsed.proposed_edits || []).map((edit) => {
const params = { ...(edit.params || {}) };
const entityIds = Array.isArray(params.entity_ids) ? params.entity_ids : [];
delete params.entity_ids;
if (entityIds.length) params.entity_count = entityIds.length;
return {
edit_id: edit.edit_id,
kind: edit.kind,
label: edit.label,
geometry_type: edit.geometry?.type || null,
params,
};
});
return JSON.stringify({
proposal_id: parsed.proposal_id,
status: parsed.status,
plan_id: parsed.plan_id,
expected_revision_id: parsed.expected_revision_id,
label: parsed.label,
proposed_edits: proposedEdits,
preview: parsed.preview,
clearance_target: parsed.clearance_target,
visualization: compactVisualization,
next_step: parsed.next_step,
});
}
async function runOpenAI({ history, toolDefs, instructions, apiKey, dataDir = DATA_DIR, onProgress = null, signal = null }) {
const tools = toolDefs.map((t) => ({
type: 'function', name: t.name, description: t.description, parameters: t.parameters,
}));
const trace = [];
let reply = null;
let previousId = null;
let input = history;
const userText = history[history.length - 1] && history[history.length - 1].content || '';
const wantsJson = looksLikeJsonRequest(userText);
const ecologyRequest = isEcologyIntent(userText) && !isPlanEditIntent(userText);
let ecologyLayerChecked = false;
let ecologyPreflightNudged = false;
let nearCapNudged = false;
let planTerminalReached = false;
for (let round = 0; round <= MAX_TOOL_ROUNDS; round += 1) {
if (signal?.aborted) break; // client disconnected — stop spending on the loop
if (!nearCapNudged && !planTerminalReached
&& round >= MAX_TOOL_ROUNDS - OPENAI_NEAR_TOOL_CAP_WARNING) {
nearCapNudged = true;
const remaining = Math.max(0, MAX_TOOL_ROUNDS - round);
input = [...input, {
type: 'message', role: 'user',
content: `You have only about ${remaining} tool rounds left. Stop nonessential discovery. Complete the required action now if ready, then answer.`,
}];
}
const payload = {
model: OPENAI_MODEL,
reasoning: { effort: OPENAI_REASONING },
instructions,
input,
...(previousId ? { previous_response_id: previousId } : {}),
};
if (!planTerminalReached) payload.tools = tools;
const data = await openaiResponses(payload, apiKey, signal);
previousId = data.id;
const calls = (data.output || []).filter((o) => o.type === 'function_call');
if (!calls.length) {
reply = openaiOutputToText(data.output);
break;
}
input = [];
for (const call of calls) {
let args = {};
try { args = JSON.parse(call.arguments || '{}'); } catch (_err) { /* ignore */ }
onProgress?.({ type: 'tool_call', tool: call.name, args, layers: layerRefsFromToolActivity(args, null) });
let result;
if (ecologyRequest && needsThematicLayerPreflight(call.name) && !ecologyLayerChecked && !ecologyPreflightNudged) {
ecologyPreflightNudged = true;
result = ecologyPreflightToolResult();
} else {
try {
result = await mcpCall(call.name, args, dataDir);
} catch (err) {
result = JSON.stringify({ error: String(err.message || err) });
}
if (isEcologyLayerInspectionTool(call.name)) ecologyLayerChecked = true;
}
onProgress?.({ type: 'tool_result', tool: call.name, layers: layerRefsFromToolActivity(args, result) });
const modelResult = toolResultForModel(call.name, result);
trace.push({ tool: call.name, args, result: traceResult(modelResult) });
input.push({ type: 'function_call_output', call_id: call.call_id, output: modelResult });
if (successfulPlanTerminalTool(call.name, result)) planTerminalReached = true;
}
if (planTerminalReached) {
input.push({ type: 'message', role: 'user', content: PLAN_TERMINAL_FINALIZE_PROMPT });
}
}
if (reply === null && !signal?.aborted) {
try {
const finalData = await openaiResponses({
model: OPENAI_MODEL,
reasoning: { effort: OPENAI_REASONING },
instructions,
input: [...input, {
type: 'message', role: 'user', content: TOOL_BUDGET_FINALIZE_PROMPT,
}],
...(previousId ? { previous_response_id: previousId } : {}),
}, apiKey, signal);
const finalText = openaiOutputToText(finalData.output).trim();
if (finalText) {
reply = finalText;
trace.push({ finalize: { provider: 'openai', tools_disabled: true,
reason: 'tool_budget' } });
}
} catch (_err) { /* retain the bounded fallback below */ }
}
if (reply === null) reply = '(GAIA reached its tool budget before completing the request.)';
if (!signal?.aborted && wantsJson && !hasContractJson(reply)) {
try {
const finalizePayload = {
model: OPENAI_MODEL,
reasoning: { effort: OPENAI_REASONING },
instructions: `${instructions}\n\n${JSON_FINALIZE_PROMPT}`,
input: [...input, { type: 'message', role: 'user', content: JSON_FINALIZE_PROMPT }],
...(previousId ? { previous_response_id: previousId } : {}),
};
const finalData = await openaiResponses(finalizePayload, apiKey, signal);
const finalText = openaiOutputToText(finalData.output).trim();
if (finalText) {
reply = finalText;
trace.push({
finalize: {
provider: 'openai',
tools_disabled: true,
requested_json: wantsJson,
reason: 'json_contract',
},
});
}
} catch (_err) {
if (process.env.OLLAMA_DEBUG) {
console.error('openai finalize JSON pass failed:', _err && _err.message ? _err.message : String(_err));
}
}
}
return { reply, trace };
}
async function runOllama({ history, toolDefs, instructions, dataDir = DATA_DIR, onProgress = null, signal = null }) {
const tools = toolDefs.map((t) => ({
type: 'function',
function: { name: t.name, description: t.description, parameters: t.parameters },
}));
const messages = [{ role: 'system', content: instructions }, ...history];
const trace = [];
const userText = history[history.length - 1].content || '';
const wantsJson = looksLikeJsonRequest(userText);
const ecologyRequest = isEcologyIntent(userText) && !isPlanEditIntent(userText);
let ecologyLayerChecked = false;
let ecologyPreflightNudged = false;
const drawPoints = new Set();
let outsideCount = 0;
let nearCapNudged = false;
let pointHintNudged = false;
let reply = null;
let lastContent = ''; // gpt-oss often writes its answer in a turn that ALSO calls a tool
let nudges = 0; // bounded recoveries from empty-final turns
let parseNudges = 0; // bounded recoveries from malformed tool-call parse errors
for (let round = 0; round <= MAX_TOOL_ROUNDS_OLLAMA; round += 1) {
if (signal?.aborted) break; // client disconnected — stop the tool loop
if (!nearCapNudged && round >= MAX_TOOL_ROUNDS_OLLAMA - OLLAMA_NEAR_TOOL_CAP_WARNING) {
nearCapNudged = true;
const remaining = Math.max(0, MAX_TOOL_ROUNDS_OLLAMA - round);
messages.push({
role: 'user',
content: `You have only about ${remaining} tool turns left. Stop gathering new evidence when ready, then output final JSON now if the user requested it.`,
});
}
let data;
try {
data = await ollamaChat({
model: OLLAMA_MODEL,
messages,
tools,
stream: false,