-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool_context.lua
More file actions
649 lines (601 loc) · 19.6 KB
/
Copy pathtool_context.lua
File metadata and controls
649 lines (601 loc) · 19.6 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
local core = require "core"
local common = require "core.common"
local config = require "core.config"
local json = require "core.json"
local permission = require "plugins.assistant.permission"
---Shared helpers used by assistant tool implementations.
---
---This module centralizes project-root checks, write confirmation, process
---formatting, HTTP helpers, and compact display formatting so individual tool
---modules stay small.
---@class assistant.tool_context
local context = {}
context.OUTPUT_LIMIT = 128 * 1024
context.FILE_CHUNK_SIZE = 64 * 1024
context.OMITTED_TOOL_ARGUMENT_PATTERN = "^%[omitted %d+ bytes from prior tool argument `[^`]+`%]$"
local confirm_write
local active_conversation
---Return the conversation whose tool call is currently executing.
---@return assistant.Conversation|nil conversation
function context.active_conversation()
return active_conversation
end
---Run a callback while exposing the active conversation to tool helpers.
---@param conversation assistant.Conversation|nil Conversation associated with the tool call.
---@param callback fun(): ...
---@return ...
function context.with_active_conversation(conversation, callback)
local previous = active_conversation
active_conversation = conversation
local ok, a, b, c, d = pcall(callback)
active_conversation = previous
if not ok then error(a) end
return a, b, c, d
end
---Yield to Pragtical's UI loop when running inside a coroutine.
function context.yield_ui()
if coroutine.isyieldable() then
core.redraw = true
coroutine.yield()
end
end
---Normalize normalize.
---@param path string|nil
---@return string|nil
function context.normalize(path)
if not path or path == "" then return nil end
local absolute = path
if not common.is_absolute_path(path) then
absolute = core.project_absolute_path(path)
end
return common.normalize_path(absolute) or absolute
end
---Handle project root for.
---@param path string
---@return string|nil
function context.project_root_for(path)
path = context.normalize(path)
if not path then return nil end
for _, project in ipairs(core.projects or {}) do
local root = common.normalize_path(project.path) or project.path
if path == root or common.path_belongs_to(path, root) then
return root
end
end
return nil
end
---Handle project roots text.
---@return string
function context.project_roots_text()
local roots = {}
for _, project in ipairs(core.projects or {}) do
if project.path and project.path ~= "" then
table.insert(roots, common.normalize_path(project.path) or project.path)
end
end
if #roots == 0 then return "none" end
return table.concat(roots, ", ")
end
---Handle project roots.
---@return string[] roots
function context.project_roots()
local roots = {}
for _, project in ipairs(core.projects or {}) do
if project.path and project.path ~= "" then
table.insert(roots, common.normalize_path(project.path) or project.path)
end
end
return roots
end
---Read root for.
function context.read_root_for(path)
path = context.normalize(path)
if not path then return nil end
return context.project_root_for(path)
end
---Handle assert project path.
---@param path string
---@return string|nil absolute
---@return string|nil err
function context.assert_project_path(path)
local absolute = context.normalize(path)
if not absolute then return nil, "missing path" end
if not context.project_root_for(absolute) then
return nil, "path is outside loaded project roots: " .. absolute .. "\nAllowed project roots: " .. context.project_roots_text()
end
return absolute
end
---Assert a writable path, asking before allowing paths outside loaded roots.
---@param path string
---@param details string|nil
---@return string|nil absolute
---@return string|nil err
function context.assert_write_path(path, details)
local absolute = context.normalize(path)
if not absolute then return nil, "missing path" end
if context.project_root_for(absolute) then return absolute end
if context.confirm("write_path", absolute, details or "Write outside loaded project roots") then
return absolute
end
return nil, "user denied writing outside loaded project roots: " .. absolute
end
---Handle assert read path.
---@param path string
---@return string|nil absolute
---@return string|nil err
function context.assert_read_path(path)
local absolute = context.normalize(path)
if not absolute then return nil, "missing path" end
if not context.read_root_for(absolute) then
if config.plugins.assistant and config.plugins.assistant.allow_any_read_path then
return absolute
end
if context.confirm("read_path", absolute, "Read outside loaded project roots") then
return absolute
end
return nil, "user denied reading outside loaded project roots: " .. absolute
end
return absolute
end
---Read path allowed without confirmation.
function context.read_path_allowed_without_confirmation(path)
local absolute = context.normalize(path)
if not absolute then return false end
if context.read_root_for(absolute) then return true end
local conf = config.plugins.assistant or {}
return conf.allow_any_read_path == true
end
---Read path requires approval.
function context.read_path_requires_approval(arguments, key)
return not context.read_path_allowed_without_confirmation(arguments and arguments[key])
end
---Read file.
---@param path string
---@return string|nil text
---@return string|nil err
function context.read_file(path)
local fp, err = io.open(path, "rb")
if not fp then return nil, err end
local chunks = {}
while true do
local chunk = fp:read(context.FILE_CHUNK_SIZE)
if not chunk then break end
table.insert(chunks, chunk)
context.yield_ui()
end
fp:close()
context.yield_ui()
return table.concat(chunks)
end
---Write file.
---@param path string
---@param text string
---@return boolean ok
---@return string|nil err
function context.write_file(path, text)
local parent = path:match("^(.*)" .. PATHSEP .. "[^" .. PATHSEP .. "]+$")
if parent and parent ~= "" then
common.mkdirp(parent)
end
local fp, err = io.open(path, "wb")
if not fp then return false, err end
text = tostring(text or "")
for index = 1, #text, context.FILE_CHUNK_SIZE do
fp:write(text:sub(index, index + context.FILE_CHUNK_SIZE - 1))
context.yield_ui()
end
fp:close()
context.yield_ui()
return true
end
---Return whether hash text is available.
function context.hash_text(text)
local hash = 2166136261
for i = 1, #text do
hash = (hash * 16777619 + text:byte(i)) % 4294967296
if i % 4096 == 0 then context.yield_ui() end
end
return string.format("%08x", hash)
end
---Handle split lines.
function context.split_lines(text)
local lines = {}
for line in ((text or "") .. "\n"):gmatch("(.-)\n") do
table.insert(lines, line)
if #lines % 200 == 0 then context.yield_ui() end
end
if text and text:sub(-1) == "\n" then table.remove(lines) end
return lines
end
---Handle optional text.
function context.optional_text(value)
if value == nil then return nil end
value = tostring(value)
local normalized = value:lower():gsub("^%s+", ""):gsub("%s+$", "")
if normalized == "" or normalized == "none" or normalized == "null" or normalized == "nil" then
return nil
end
return value
end
---Handle contains omitted tool argument.
function context.contains_omitted_tool_argument(value)
if type(value) == "string" and value:match(context.OMITTED_TOOL_ARGUMENT_PATTERN) then
return true
end
if type(value) == "table"
and type(value.prior_tool_call_summary) == "string"
and value.omitted_content_bytes ~= nil
then
return true
end
if type(value) ~= "table" then return false end
for _, item in pairs(value) do
if context.contains_omitted_tool_argument(item) then return true end
end
return false
end
---Return text safe for provider JSON string payloads.
---@param text any
---@return string sanitized
function context.sanitize_text(text)
text = tostring(text or "")
if string.uclean then
text = text:uclean("<invalid-utf8>", true)
end
local out = {}
local i = 1
while i <= #text do
local byte = text:byte(i)
if (byte < 0x20 or byte == 0x7f) and byte ~= 0x09 and byte ~= 0x0a and byte ~= 0x0d then
table.insert(out, string.format("\\x%02X", byte))
else
table.insert(out, text:sub(i, i))
end
i = i + 1
if i % 4096 == 0 then context.yield_ui() end
end
return table.concat(out)
end
---Return whether raw bytes are likely binary rather than searchable text.
---@param text string
---@return boolean binary
function context.looks_binary(text)
text = tostring(text or "")
if text:find("%z") then return true end
local limit = math.min(#text, 8192)
if limit == 0 then return false end
local controls = 0
for i = 1, limit do
local byte = text:byte(i)
if byte < 0x20 and byte ~= 0x09 and byte ~= 0x0a and byte ~= 0x0c and byte ~= 0x0d then
controls = controls + 1
end
end
return controls / limit > 0.05
end
---Handle limit text.
function context.limit_text(text, limit)
limit = tonumber(limit) or context.OUTPUT_LIMIT
text = tostring(text or "")
if #text <= limit then
return context.sanitize_text(text), false, 0, #text
end
return context.sanitize_text(text:sub(1, limit)) .. string.format("\n... truncated %d bytes ...", #text - limit),
true,
#text - limit,
#text
end
---Handle limited.
function context.limited(text, limit)
local output = context.limit_text(text, limit)
return output
end
---Compact provider text result.
---@param result any
---@param label string
---@return string
function context.compact_provider_text_result(result, label)
result = tostring(result or "")
local limit = 48000
if #result <= limit then return result end
local head = result:sub(1, 32000)
local tail = result:sub(-8000)
return table.concat({
tostring(label or "tool result") .. " compacted for provider context",
"bytes: " .. tostring(#result),
"hash: " .. context.hash_text(result),
"",
head,
"",
string.format("... omitted %d bytes from tool result ...", math.max(0, #result - #head - #tail)),
"",
tail
}, "\n")
end
---Handle project relative.
function context.project_relative(path)
local root = context.project_root_for(path)
return root and common.relative_path(root, path) or tostring(path or "")
end
---Handle edit summary.
function context.edit_summary(action, absolute, old_text, new_text)
old_text = tostring(old_text or "")
new_text = tostring(new_text or "")
local lines = {
string.format("%s: %s", action, context.project_relative(absolute)),
string.format("bytes: %d -> %d", #old_text, #new_text)
}
if old_text ~= "" then
table.insert(lines, "old_hash: " .. context.hash_text(old_text))
end
table.insert(lines, "new_hash: " .. context.hash_text(new_text))
return table.concat(lines, "\n")
end
---Handle process output.
function context.process_output(proc, max_output_tokens)
local stdout, stderr = {}, {}
while true do
local out = proc:read_stdout(4096)
if not out or out == "" then break end
table.insert(stdout, out)
end
while true do
local errout = proc:read_stderr(4096)
if not errout or errout == "" then break end
table.insert(stderr, errout)
end
local limit = tonumber(max_output_tokens) or context.OUTPUT_LIMIT
local out_text, out_truncated, out_omitted, out_bytes = context.limit_text(table.concat(stdout), limit)
local err_text, err_truncated, err_omitted, err_bytes = context.limit_text(table.concat(stderr), limit)
return {
stdout = out_text,
stderr = err_text,
stdout_bytes = out_bytes,
stderr_bytes = err_bytes,
stdout_truncated = out_truncated,
stderr_truncated = err_truncated,
stdout_omitted_bytes = out_omitted,
stderr_omitted_bytes = err_omitted
}
end
---Format process result.
function context.format_process_result(result)
return string.format(
"exit_code: %s\ntimed_out: %s\nwall_time_ms: %s\nsession_id: %s\nstdout_bytes: %s\nstderr_bytes: %s\nstdout_truncated: %s\nstderr_truncated: %s\nstdout:\n%s\nstderr:\n%s",
tostring(result.exit_code),
tostring(result.timed_out == true),
tostring(result.wall_time_ms or ""),
tostring(result.session_id or ""),
tostring(result.stdout_bytes or ""),
tostring(result.stderr_bytes or ""),
tostring(result.stdout_truncated == true),
tostring(result.stderr_truncated == true),
result.stdout or "",
result.stderr or ""
)
end
---Handle run process.
---@param command string|string[]
---@param cwd string|nil
---@param timeout_ms integer|nil
---@return boolean ok
---@return table|string result
function context.run_process(command, cwd, timeout_ms)
local proc, err = process.start(command, {
cwd = cwd,
timeout = timeout_ms or 30000,
stdout = process.REDIRECT_PIPE,
stderr = process.REDIRECT_PIPE,
stdin = process.REDIRECT_DISCARD
})
if not proc then
return false, "could not start process: " .. tostring(err)
end
local stdout, stderr = {}, {}
local started = system.get_time()
---Drain any output still buffered in the pipes after the process exits or is
---killed, then build the result. Without this final drain, output produced
---between the last incremental read and process exit is lost.
local function finish(exit_code, timed_out)
while true do
local out = proc:read_stdout(4096)
if not out or out == "" then break end
table.insert(stdout, out)
end
while true do
local errout = proc:read_stderr(4096)
if not errout or errout == "" then break end
table.insert(stderr, errout)
end
local out_text, out_truncated, out_omitted, out_bytes = context.limit_text(table.concat(stdout))
local err_text, err_truncated, err_omitted, err_bytes = context.limit_text(table.concat(stderr))
return {
exit_code = exit_code,
timed_out = timed_out,
wall_time_ms = math.floor((system.get_time() - started) * 1000),
stdout = out_text,
stderr = err_text,
stdout_bytes = out_bytes,
stderr_bytes = err_bytes,
stdout_truncated = out_truncated,
stderr_truncated = err_truncated,
stdout_omitted_bytes = out_omitted,
stderr_omitted_bytes = err_omitted
}
end
while true do
local out = proc:read_stdout(4096)
local errout = proc:read_stderr(4096)
if out and out ~= "" then table.insert(stdout, out) end
if errout and errout ~= "" then table.insert(stderr, errout) end
local code = proc:wait(0)
if code ~= nil then
return true, finish(code, false)
end
if timeout_ms and (system.get_time() - started) * 1000 >= timeout_ms then
proc:kill()
return false, finish(-1, true)
end
context.yield_ui()
end
end
---Handle shell command.
function context.shell_command(command)
local shell = os.getenv("SHELL") or "/bin/sh"
return { shell, "-c", command }
end
---Parse url.
function context.parse_url(url)
url = tostring(url or "")
local protocol, host = url:match("^(https?)://([^/:?#]+)")
if not protocol then return nil, "invalid URL: expected http:// or https://" end
return {
protocol = protocol,
host = host
}
end
---Handle urlencode.
function context.urlencode(str)
if not str then return "" end
return (tostring(str):gsub("([^%w%-._~])", function(c)
return string.format("%%%02X", string.byte(c))
end))
end
---Handle configured web timeout.
function context.configured_web_timeout(timeout_ms)
return (tonumber(timeout_ms) or tonumber(config.plugins.assistant.web_timeout_ms) or 10000) / 1000
end
---Handle host allowed.
function context.host_allowed(host)
local allow = config.plugins.assistant and config.plugins.assistant.web_allow_hosts
if type(allow) == "string" then
for item in allow:gmatch("[^,%s]+") do
if item == host then return true end
end
elseif type(allow) == "table" then
for _, item in ipairs(allow) do
if item == host then return true end
end
end
return false
end
---Handle web request requires approval.
function context.web_request_requires_approval(arguments)
local url = context.optional_text(arguments and (arguments.url or config.plugins.assistant.web_search_url))
if not url then return false end
local parsed = context.parse_url(url)
return not (parsed and context.host_allowed(parsed.host))
end
---Handle command requires approval.
function context.command_requires_approval(arguments)
local classification = permission.classify_command(
arguments and arguments.command,
arguments and arguments.cwd,
context.project_roots()
)
return permission.requires_approval(classification)
end
---Normalize headers.
function context.normalize_headers(headers)
if type(headers) == "table" then return headers end
if type(headers) == "string" and headers ~= "" then
local decoded = json.decode(headers)
if type(decoded) == "table" then return decoded end
end
return {}
end
---Handle http request.
---@param method string
---@param url string
---@param headers table|string|nil
---@param body string|nil
---@param timeout_ms integer|nil
---@return boolean ok
---@return table|string result
function context.http_request(method, url, headers, body, timeout_ms)
local ok_http, http = pcall(require, "core.http")
if not ok_http then
return false, "HTTP tools are unavailable because networking is disabled."
end
local done = false
local cancelled = false
local result_ok, result_err, result_body, result_info
local timeout = context.configured_web_timeout(timeout_ms)
local started = system.get_time()
http.request(method, url, {
headers = context.normalize_headers(headers),
body = context.optional_text(body),
decode_json = false,
timeout = timeout,
is_cancelled = function() return cancelled end,
on_done = function(ok, err, result, info)
result_ok = ok
result_err = err
result_body = result
result_info = info
done = true
end
})
while not done do
if system.get_time() - started >= timeout then
cancelled = true
return false, "web request timed out", nil, { url = url }
end
context.yield_ui()
end
return result_ok, result_err, result_body, result_info
end
---Format headers.
function context.format_headers(headers)
local out = {}
for key, value in pairs(headers or {}) do
if type(value) == "table" then value = table.concat(value, ", ") end
table.insert(out, tostring(key) .. ": " .. tostring(value))
end
table.sort(out)
return table.concat(out, "\n")
end
---Handle extract path.
function context.extract_path(value, path)
path = context.optional_text(path)
if not path then return value end
for part in path:gmatch("[^%.]+") do
if type(value) ~= "table" then return nil end
local index = tonumber(part)
value = index and value[index] or value[part]
end
return value
end
---Handle looks like html.
function context.looks_like_html(text)
text = tostring(text or ""):sub(1, 512):lower()
return text:find("<!doctype%s+html")
or text:find("<html[%s>]")
or text:find("<head[%s>]")
or text:find("<body[%s>]")
end
---Handle git command.
function context.git_command(...)
return { "git", ... }
end
---Set the confirm write.
---@param callback fun(action: string, path: string, details?: string): boolean
---@return function|nil previous
function context.set_confirm_write(callback)
local previous = confirm_write
confirm_write = callback
return previous
end
---Handle confirm.
---@param action string
---@param path string
---@param details string|nil
---@return boolean
function context.confirm(action, path, details)
if confirm_write then
return confirm_write(action, path, details)
end
core.warn("Assistant: tool action '%s' denied for %s; no confirmation handler installed.", action, path)
return false
end
return context