← Reference

Lua plugin calls

Everything a Lua plugin does goes through the kcode table.

Full notes from the app

Each call below has its arguments, the capability it needs and what it returns. A plugin declares capabilities in the [capabilities] table of its plugin.toml (kv = true, "net.http" = []). A call the plugin hasn't declared is still on kcode, but raises an error naming the plugin, the capability and the line to add. An error a call raises can be caught with pcall.

A Lua script skill gets the calls marked “also in script skills”, gated by the capabilities: in its SKILL.md frontmatter, and its run(args, ctx) gets ctx.state, the skill's own folder for state.

The sandbox has Lua's table, string, math and utf8 libraries, and leaves out os, io, package, dofile, loadfile and debug. require("lib.words") loads lib/words.lua, or lib/words/init.lua, from the plugin's own folder: a script skill's from its skill folder.

47 entries · kcode 0.6.5097

47 shown
CallArgumentsCapabilityReturnsWhat it does
kcode.register_toolname, desc?, handler?, opts?nonenoneAdds a tool to the session. opts.schema declares the tool's arguments as a JSON Schema object, and opts.read_only = true marks the tool side-effect-free. opts.path_arguments lists the arguments that name files, { "path" }, or {} for none: a read-only tool needs permission when one of them names a place in permissions.secret_paths, and with no list every argument counts, so a tool whose arguments are queries or text should give {}. A list naming an argument the schema doesn't list refuses the tool, and anything but a list of names fails the load. A tool without a schema is offered to the model as taking an object with no listed arguments, so declare the arguments its handler reads: when a handler reads an argument its schema doesn't declare and the call didn't pass, the plugin's Activity names the tool and the argument, once per load, and so does the log. A schema that names another type (schema = { type = "string" }) is refused, since a tool's arguments are one JSON object and no model could call it. A tool name must be 1 to 64 ASCII letters, digits, _ or -, starting with a letter or _: the names every provider accepts. A refused tool leaves the plugin's other tools loaded, the log names it, and kcode plugins validate fails naming it. Without a handler, the tool's handler is read from kcode.tool_handler once main.lua returns. A tools = { name = { description = …, handler = …, schema = …, read_only = … } } table in main.lua declares tools too; its entries take schema, read_only and path_arguments as their own fields. Registering one name twice fails the load.
See kcode.tool_handler
kcode.tool_handlernonenoneA table for the handlers of tools registered without one: kcode.register_tool("search", "Search the notes"), then kcode.tool_handler.search = function(args) … end. kcode reads it once main.lua returns, and a tool whose handler is still missing fails the load.
See kcode.register_tool
kcode.register_commandname, summary, handlernonenoneAdds a slash command: /name args runs handler(args) in the daemon and shows the markdown it returns (a string, {markdown = …}, or nil for nothing) in the chat as a bubble, never a model turn. The slash menu lists it tagged plugin with its summary (or "from the <plugin> plugin"). A built-in command, a skill or a markdown command of the same name always wins, and between plugins the one loaded first answers. A name is lowercase letters, digits, - and _; registering one name twice in one plugin fails the load.
kcode.on_eventkind, handlerhooksnoneRuns handler on every event of kind: a catalogued core.* point, among them core.fs.change (the project watcher, gitignore-filtered), core.timer.tick (the crons in eventsource_timer.crons, heard by every plugin, and the plugin's own schedules, heard only by it) and the core.app.* turn, tool and subagent events, another plugin's plugin.<id>.<event>, or webhook:<name>: an authenticated POST to the daemon's loopback webhook listener (session_daemon.webhook_*) or a kcode trigger <name> fire, whose data carries {name, text, json?}, json riding when the body parses. The handler receives {kind, source, intent, ts, data}: ts is when the event fired, in milliseconds since the Unix epoch, and data holds the event's own fields, Event/Hook Surfaces lists them for each event. Every handler for a kind runs on one fire, and each run's end, or its Lua error, shows in the /control drawer as <cp:hook-fired>. A retired name (turn-finished, which is core.app.turn-finished now), an unknown core.* name (naming near misses) or a point nothing fires yet fails the load; under an [events] table the kind must be listed under watch.
See #events kcode.on
kcode.onpoint, handlerhooksnoneWatches one catalogued core.* point or another plugin's plugin.<id>.<event>: the dispatch and handler of kcode.on_event, with a verb that says the plugin only watches. A retired, unknown or planned name fails the load naming the fix, and so does a plugin.* event given to kcode.intercept, since another plugin's events are watch-only; under an [events] table the point must be listed under watch.
See #events kcode.on_event kcode.intercept
kcode.interceptpoint, handlerhooks, plus prompt at core.prompt.buildnoneAttaches to one of the interceptable core.* points (core.input.submit, core.prompt.build, core.context.build, core.provider.request, core.provider.error, core.tool.pre, core.tool.post, core.tool.error, core.shell.pre, core.command.pre, core.skill.pre, core.subagent.pre, core.continuation.decide, core.compaction.gate). The handler receives the point's payload table (the fields a watcher sees) and returns nil to pass, {veto = "reason"} to block, or {rewrite = <the table with your edits>}. Handlers run in plugin load order on each plugin's own task, a rewrite threads to the next handler, the first veto wins, and a handler that errors or times out is skipped (fail-open). A veto is named by the plugin that cast it, never the bridge: a vetoed tool call fails with vetoed by plugin "<name>": reason, a vetoed tool result becomes that error, and a vetoed provider request ends the turn with The plugin "<name>" stopped the turn: reason. A veto at core.continuation.decide (asked after every round, one that called tools included) ends the turn there; one at core.compaction.gate puts the due automatic compaction off, at most compaction.max_deferrals times, and overflow recovery never asks the gate; one at core.input.submit ends the turn before any provider call; one at core.shell.pre refuses the call that would run the command; one at core.command.pre or core.skill.pre refuses the command or the skill run; one at core.subagent.pre fails the spawn with subagent spawn vetoed by plugin "<name>": reason before the child is registered. core.tool.error takes no veto (the failure already happened) so one cast there is logged and dropped. A rewrite lands on the payload key by key: the fields the handler returns replace those fields and the ones it leaves out stay, and kcode.null clears a field. Only the point's rewritable fields land; any other is ignored and logged: text at core.input.submit and core.command.pre; messages at core.context.build; inputs at core.skill.pre; action, delay_ms and model at core.provider.error; max_tokens, temperature, effort, thinking, stop_sequences and tools at core.provider.request (model is read-only, tools may only drop names, and a bad value such as an unknown effort name refuses the whole rewrite); args at core.tool.pre; content and is_error at core.tool.post; content at core.tool.error, the error text the model reads, while the transcript keeps the original; vote and reason at core.continuation.decide; prompt, kind, model and effort at core.subagent.pre; a rewritten kind must be registered and the child takes its tools and permission mode, and a rewritten model is a catalogue label or id a connected provider serves, nil clearing it so the child takes the session's; one that doesn't resolve fails the spawn naming the plugin and the field. Nothing at core.shell.pre is rewritable: rewrite a call's args at core.tool.pre. **core.prompt.build** needs the prompt capability too, and fires once per session build (start, resume, /reload) never at a turn or a round. The payload is the system prompt as named sections: prompt.sections, a table of name → text, and prompt.order, the names in assembly order, identity, how-to-work, tools, style, rich-output, memory, recall, then output-style when the session has one, working-folder, project-context when the session has it, control-plane, and memory-index and goal when the session has those; a subagent's turn adds its kind's instructions after them, and a subagent in its own worktree that folder. Set prompt.sections.style = "…" to replace a section, hand back the old text plus more to append, leave a name out of sections to drop it, add a name to add one, and reorder with order (a listed name that is no section is skipped, an unlisted section keeps its place after the listed ones, and a name listed twice refuses the rewrite). control-plane only grows: its new text must start with the current one, because it teaches the reply format the loop reads, and a section set to nothing is refused; drop it instead. The prompt the plugins hand back is the one the session runs on for the whole conversation, so a change lands at the next session, resume or /reload, like an AGENTS.md edit. A watch-only or planned point, or any plugin.* event, fails the load naming what it supports; under an [events] table the point must be listed under intercept.
See #events kcode.on_input kcode.on_tool kcode.null
kcode.provideslot, handlerhooksnoneAnswers one of the three provide slots. core.model.select: return {model = "…"}, the model the turn runs on, a name no keyed provider serves is refused and the turn keeps its own. core.continuation.decide: return {vote = "continue" or "stop", reason = "…"}, the plugin's ballot after each round, a stop ends the turn whatever the round did, and a continue counts only on a round that would otherwise stop, since the built-in safety stops and the model's done outrank it. core.compaction.summarize: return {summary = "…"} to write the compaction summary yourself (the model is not asked) or {instructions = "…"} to steer the summarizer beside the user's /compact text; given both, the summary wins. The handler receives the slot's payload table and returns a table, or nil to decline; an error, a timeout or an answer that is no table reads as a decline, so the built-in behaviour stands. One plugin wins each slot: a project plugin beats a user plugin beats a built-in, then by name, never load order. A point with no slot (core.tool.pre) fails the load naming what it supports, and so does providing one slot twice in one plugin; under an [events] table the slot must be listed under provide.
See #events
kcode.on_cronspec, handler, opts?hooksnoneRegisters a schedule worked out at load (from a setting, say) where spec is a plain period ("30s", "5m", "15d", "2w": ms, s, m, h, d or w) or a six-field cron expression in local time, and opts.fires_per is "app" (the default), "project" or "session" (an app plugin takes only "app"), as in the manifest's [[triggers.every]]. opts.durable = true keeps the schedule's next time across restarts, so kcode.on_cron("15d", handler, {durable = true}) fires 15 days after it was first set however often kcode quits in between; opts.missed says what a durable schedule does about a time that passed while kcode wasn't running: "once" (the default) fires it once at start, "skip" waits for the next. A durable schedule can't fire per session, and missed needs durable. An unknown option or value fails the load, and so does a bad spec, naming the schedule. The handler alone receives that schedule's fires, shaped as kcode.on_event's, and a fire runs plugin handlers only, never an agent turn.
kcode.on_inputhandlerinput-transform or hooksnoneThe short form of kcode.intercept("core.input.submit", …): runs on every prompt the user submits, before the model is chosen. The handler receives {session_id, text} and returns nil to pass, a string or {text = …} to rewrite the text the model reads (the transcript records it too, and only the ↑ prompt history keeps what was typed) or {veto = "reason"} to end the turn with an error naming the plugin. It sits in the intercept chain in plugin load order, 5 s per plugin, fail-open, so a kcode.intercept handler after it reads the rewritten text.
See kcode.intercept
kcode.on_toolhandlertool-gate or hooksnoneThe short form of a gate at core.tool.pre: runs before every tool call, the model's and other plugins' kcode.run_tool calls alike. The handler receives {session_id, round, call_id, tool, args}, the args as an earlier plugin's rewrite left them, and no call_id for a run_tool call, and returns nil to allow or {veto = "reason"} to block: the call then fails with tool t vetoed by plugin "x": reason, which never reads as a denial of the permission engine. It only gates; to change the args, intercept the point. To gate the commands kcode runs, intercept core.shell.pre: its handler receives {session_id, round, call_id, tool, command} (the command a call of bash, shell_spawn or shell_proceed is about to run) so one gate covers every way a command runs, where a gate on bash alone misses the other two; another plugin's kcode.exec meets it too, with tool = kcode.exec and the program's argv. Gates run in plugin load order, the first veto wins, each plugin gets 5 s, and every failure (an error, a timeout, a plugin gone) lets the call through: the permission engine stays the security boundary.
See kcode.intercept
kcode.emitkind, data?hooksnonePublishes a custom event other plugins hear with kcode.on_event("plugin.<emitter>.<kind>", …). Its kind and source both name the plugin, so an emission can never pass for a kcode event and every listener sees which plugin spoke. The emitter's own handlers don't hear it, a fire never starts an agent turn, and past 120 a minute per plugin the call raises an error rather than dropping the event. An empty kind, or one over 128 characters, raises too.
kcode.injecttextinjectnoneWakes the plugin's session with text the agent reads, on the <cp:plugin-inject> channel: a turn under way sees it at its next round, and an idle session starts a turn with it, so a watcher plugin can speak for itself instead of waiting for the user. Empty text is dropped, and the call doesn't wait for the text to arrive.
See <cp:plugin-inject>
kcode.notifytitle, body?, opts?notifytrue, or false and the reasonPosts a message to the notification center. From a tool the agent called it is an Agent message ("<title> — <body> (via <plugin>)"); from anywhere else (an event or schedule handler, a command) the plugin's own ("<plugin>: <title> — <body>"). It becomes a macOS banner while the window is not in front, and is capped per session by session_daemon.agent_notify_* (5 per 60 s by default). A notice posted while the session starts (from the top of main.lua, say) is not posted: post it from a core.session.start handler. In a script skill the user ran the notice is the skill's, and in one the agent ran it speaks for the agent. opts.command offers a slash command line, such as "/review src": the notice's drawer row and its card get a Run button that runs it in the plugin's own session (resumed first if it stopped) and opens that session. It must start with / and a name, be one line and hold at most 200 characters; anything else raises, as does any other key in opts. The macOS banner offers no button. It returns true once the notice is posted, or false and the reason it was not. In kcode -p, which keeps no notification center, the call raises.
Also in script skills
kcode.logmessage, level?nonenoneWrites a line naming the plugin to the app log, under target kcode::plugin, and to the plugin's activity: the record Settings › Plugins shows, which keeps the newest 200 entries with the plugin's loads, unloads and handler failures. level is trace, debug, info (the default), warn or error; an unknown level raises an error naming the valid set.
kcode.run_toolname, args?run-tool{structured, truncated}Runs any tool of the session on the plugin's behalf. The permission engine decides each call with the plugin named as the caller, plugin:<name>, so rules and permission prompts govern it as they do the agent's calls, and a waiting prompt names the plugin. The call then passes the core.tool.pre chain the model's calls pass: the watch fires with round 0, other plugins' intercepts and kcode.on_tool gates cover it, a veto fails it naming the plugin and a rewrite changes the args that run, but not the caller's own handlers, since its task is mid-call; core.app.tool-started and core.app.tool-finished fire for it too. The plugin's time limit stands still while a permission prompt or question is open in the session. structured is the value the model would see. A denial, a veto, a tool error or an unknown tool raises an error with the reason. A script skill may call only the tools its SKILL.md lists under tool-dependencies.
Also in script skills
kcode.spawn_subagent{prompt, kind?, name?}spawn-subagent{name}Starts a subagent of kind (general when left out) in the background; its model comes from the kind's frontmatter or the /subagent pool, as an agent's spawn does. The call returns once the spawn's core.subagent.pre gate lets the child through: name is the child's name (plugin:<plugin>, or plugin:<plugin>:<label>) as the subagent panel and /jobs show it. The result arrives as the core.app.subagent-finished event carrying that name (with success, final_text, rounds and error), and reaches the agent as a <cp:subagent> notice that wakes an idle session, unless the child was stopped. An unknown kind, a model no connected provider serves, the rate cap (5 spawns per 600 s per plugin by default, plugin_host.spawn_subagent.*), the session's subagent limits or another plugin's refusal at core.subagent.pre raises an error. /jobs kill stops a runaway child.
kcode.ask_userquestion | {question, options?, fields?}, fn?none{selected, other_text, field_values, cancelled, reason}; nothing when given fnAsks the user a question in the window the agent's questions use: a string, or {question, options?, fields?}. Without fn it waits for the answer and returns it, which it can only while one of the plugin's tools runs. The wait has no time limit, and the plugin's other handlers wait until it ends. With fn it returns at once, from anywhere (an event handler, a schedule, a slash command, a timer, main.lua) and calls fn(answer) once the user answers, however long that takes; the question names the plugin as its asker, Esc on a turn leaves it open, and it closes when the plugin unloads. A question asked while no window shows the session waits for one: the session's tile shows that it needs input, and opening the session shows the question. A plugin can have plugin_runtime_lua.max_questions (10) waiting. An answer with nothing chosen is cancelled, and its reason says why: dismissed when the user closed the question, no_user in a headless run.
kcode.settings.getkeynonethe setting's value, or nil for a key the plugin doesn't declareReads one of the plugin's settings: the default its plugin.toml [settings] table declares, under the user's [plugins.<name>] config, and a secret setting from the value saved in Settings › Plugins (nil while none is).
kcode.sessionnone{id, project_root, project, title}, or nilThe plugin's own session, read from the stored session at each call, so a /rename shows at once. project is the name the session's tile shows (a worktree session's base checkout) and project_root and title are left out when the session has none. It is nil before the session has an id (kcode -p before its first turn), and it names no other session.
kcode.presencepresence{app_focused, in_view, idle, idle_seconds, screen_locked}, or nilWhether the user is at the Mac and sees the plugin's session, read at each call. app_focused is true while a kcode window is the active window, and in_view while a kcode window shows the session: its tile maximized or in the grid, or its row or tab selected. A window counts only while the screen is unlocked and macOS lists one of its windows as on screen, so a minimized or hidden kcode, or one on another Space, counts as neither; a window another app covers still counts. idle is true once no keyboard, mouse or trackpad input has come for session_daemon.presence_idle_secs (300), and idle_seconds is how long it has been. screen_locked is true while the lock screen is up. It is nil while main.lua loads, before the daemon binds the session, and kcode -p raises that it is not wired. Watch core.app.presence-changed to hear each change instead of asking.
kcode.sessions.open{cwd, prompt?, title?}sessions.open{id, folder}Opens a new session in folder cwd (an absolute path, ~/…, or a path relative to the plugin's own session's folder) and returns once it runs: id is the new session's and folder the folder it opened in, its links resolved. prompt becomes its first turn, sent as the plugin's: the chat shows it under the plugin's name, not as typed by the user. title names it. A notice under the new session names the plugin that opened it, and a window showing the plugin's session gives the new one a tile. A folder that doesn't exist or is a file, the daemon's cap (5 opens per 600 s per plugin by default, session_daemon.plugin_open_*) or a kcode -p run, which has no daemon, raises an error. It works once the plugin's session has started, not while main.lua loads; call it from a tool, a command, an event or a timer. The new session's project needs trust as any other: until the user trusts it, its own plugins, hooks and config don't run.
kcode.sessions.list{project?, since_unix_ms?, limit?, after?}history.read or history.read-all{sessions, next}The sessions of the plugin's own project, its own session among them, the newest made first; a worktree session counts as its base checkout's project. Each is {id, project_root, project, project_folder, title, model, created_unix_ms, last_unix_ms}: project_root is the folder it ran in, project the name its tile shows, project_folder its project's folder, as project takes it, model the model it chose or else the default it last ran on, and last_unix_ms when its newest record was written; what a session lacks is nil. project = "all" lists every project and a project folder's absolute path lists that project; past the plugin's own project both need history.read-all, which a refusal names. since_unix_ms keeps the sessions made or written to since then, and limit asks for fewer than plugin_host.history.list_max_sessions (100). Pass next as after to read the next page; it is nil on the last. The install review asks for the grant, since a session holds whatever was typed or read in it, tool output included.
kcode.sessions.read{session, after?, kinds?, limit?}history.read or history.read-all{records, next, more}A page of one session's records, oldest first, as the chat showed them. Each is {seq, at_unix_ms, turn, truncated, kind} and its kind's fields: user, text, by (nil for the user, else hook:<name>, trigger:<name> or plugin:<name>) and images, how many it carried; assistant, text, the reply the chat showed; reasoning, notice and error (text; tool_call) call_id, tool and args, a table; tool_result (call_id, which matches its call, content, is_error and images; turn) model and by_user; and user_shell, a ! command once it ended, command, output, exit_code and status. turn is the id of the turn a record was written in, nil outside one, and truncated says text or arguments were cut to plugin_host.history.text_max_bytes (64 KiB). kinds lists the kinds to return; left out, it returns every kind but reasoning. The messages kcode writes for the model alone (a compaction summary, a channel note) are left out. A page holds at most limit records, plugin_host.history.read_max_records (500) and read_max_bytes (1 MiB); more says the session holds more, and next, passed as after, reads on: at the end it reads what the session wrote since. A session of another project needs history.read-all, which a refusal names.
kcode.exec{argv, cwd?, stdin?, timeout_ms?}exec{code, stdout, stderr, truncated}Runs a program on this Mac with no shell and waits for it: argv is the program and its arguments, a list of strings, so nothing in them is expanded or split. cwd is the folder it runs in: an absolute path, ~/…, or a path relative to the plugin's session's folder, which is the default. stdin is the text it reads; without it it reads nothing. code is its exit code, nil when a signal ended it, stdout and stderr its output as bytes, each kept to plugin_host.exec.max_output_bytes, and truncated says one was cut. The program runs in kcode's own environment. The install review asked for the grant, so no call asks the user; a deny rule of the user's that refuses the same bash command refuses it in every mode, and so does another plugin's veto at core.shell.pre, which sees the argv. timeout_ms stops the program sooner than the handler's own limit, plugin_runtime_lua.max_execution_seconds, which stops it too. A refusal, a folder that doesn't exist, a program that can't start or a timeout raises an error.
kcode.jobs.start{prompt, cwd?, model?, budget?, tools?}jobsthe job's idRuns the model in the background on prompt and returns the job's id at once. The job runs as a subagent of the plugin's session named plugin:<name>, so /jobs lists it and /jobs kill stops it, and it counts against the cap kcode.spawn_subagent has, plugin_host.spawn_subagent.*. cwd is the folder it runs in: an absolute path, ~/…, or a path relative to the plugin's session's folder, which is the default. model is the model it runs on; without it, the model the session's subagents use. budget is the most tokens its provider calls may use, input and output together: the job stops at the first round that starts past it. tools names the tools it may call, each one the manifest's jobs list names; without it, it calls none. Its calls pass the session's permission rules as a subagent's do, so one may ask the user, naming plugin:<name>. Its answer arrives as core.app.job-finished {session_id, id, owner, ok, text, error}, which only this plugin hears, and a watch there needs the jobs grant too; the agent gets no notice of it. A tool the jobs list leaves out, a folder that doesn't exist, a model no connected provider serves, a tool the session doesn't have, the cap or another plugin's veto at core.subagent.pre raises an error.
kcode.waits.listanswer-waitsa list of {what, request_id, agent, since_unix_ms, …}The permission asks and questions the plugin's own session waits on that the plugin may answer, oldest first. Each has what (permission or question) request_id, which kcode.waits.answer names, agent, the subagent or plugin that asked (nil for the session's own turn), and since_unix_ms, when it began. A permission adds tool, title and body, as the prompt shows them; a question adds header, question, options (its labels, in order), multi_select and allow_other. It leaves out the questions kcode asks itself (a worktree conflict, an /undo confirm), a question with fields to fill, such as a password, and every wait the plugin or one of its children raised, so a plugin can't approve its own calls. kcode -p, which has no daemon, raises that it is not wired.
kcode.waits.answer{request_id, choice, other?, reason?}answer-waitsnoneAnswers one of kcode.waits.list()'s waits as a window would, and closes it in every window. A permission takes choice = "allow", which allows the call this once, or "deny", with an optional reason the agent reads after denied by plugin "<name>"; a plugin can't allow a call always, and a deny rule of the user's has refused the call before any prompt. A question takes one of its option labels, or a list of them where it takes several, and other text of its own where it takes some. The chat says which plugin answered and how (Plugin "approver" allowed the fs_write call once.). A wait the plugin may not answer, a choice the wait doesn't take, or a wait already answered raises a catchable error and leaves the wait as it was. Call it from a tool, a command, an event or a timer: core.app.waits-changed tells the plugin when a wait begins.
kcode.plugins.stage{name, files}plugins.stage{name, folder, replaced}Writes a plugin for the user as a draft, which Settings › Plugins lists under Drafts, marked awaiting review. Nothing is installed until the user reviews it there and installs it. files maps each file's path in the plugin's folder, its parts joined by /, to the file's text, and holds a plugin.toml that names the plugin name. A draft is a Lua plugin or a content bundle that loads as kcode plugins validate loads a plugin, of at most plugin_drafts.max_files files (64) and max_bytes (1 MiB) in all, and at most max_drafts drafts (16) wait at once. folder is the draft's folder, and replaced says it replaced the plugin's own earlier draft of name; another plugin's draft of that name is refused until the user installs or discards it. A draft installs into the user's plugins folder, where it replaces the user's own plugin of that name and keeps its settings, secrets and switch; a built-in, linked or project plugin of that name refuses it. A new draft posts a notification that opens Settings › Plugins. A refusal raises a catchable error and keeps nothing. kcode -p, which has no daemon, raises that it is not wired, and so does a call while main.lua loads.
kcode.plugin_namenonenoneThe plugin's own name, a string.
kcode.nullnonenoneJSON null in both directions: a payload field with no value arrives as kcode.null, not nil, and a rewrite sets a field to it to clear the field, Lua's nil removes the key, which leaves the field as it was. kcode.json reads and writes it as null.
kcode.nownonean integer: milliseconds since the Unix epochThe time now.
Also in script skills
kcode.datems?none{year, month, day, hour, min, sec, wday, yday}The calendar fields of ms, or of now, in the Mac's time zone; wday is 1 for Sunday.
Also in script skills
kcode.afterms, fnnonethe timer's id, for kcode.cancelRuns fn once, with no arguments, after ms milliseconds. It runs between the plugin's other calls, under plugin_runtime_lua.max_execution_seconds, and an error in it lands in the plugin's activity. A plugin that only sets timers at the top of main.lua still runs them, and every waiting timer goes when the plugin unloads or its session ends. A plugin may have plugin_runtime_lua.max_timers timers waiting (1,000 by default); past it the call raises an error.
See kcode.cancel
kcode.cancelidnonetrue when a timer was waiting; false for nil or a timer that already ranStops a timer kcode.after started that is still waiting.
See kcode.after
kcode.json.encodevaluenoneJSON text, a stringTurns a Lua value into JSON text: kcode.null is null, and an empty table made by kcode.json.decode from [] stays []. A value JSON can't hold raises an error.
Also in script skills
See kcode.json.decode kcode.null
kcode.json.decodetextnonethe value the text holds, null as kcode.nullReads JSON text into a Lua value: null is kcode.null, and [] an empty table that encodes back to []. Text that is not JSON raises an error.
Also in script skills
See kcode.json.encode kcode.null
kcode.kv_getkeykvthe stored value, or nilReads a key of the plugin's durable storage. The storage survives sessions and holds any value JSON can hold, kept apart for each plugin (one plugin never reads another's keys) in the project's .kcode/storage.db for a project plugin and in ~/.kcode/storage.db for a user plugin. The kv_* calls work at the top of main.lua and in handlers alike.
See kcode.kv_set kcode.kv_list
kcode.kv_setkey, valuekvnoneStores value at key, replacing what was there. A nil value raises an error: use kcode.kv_delete to remove a key.
See kcode.kv_get kcode.kv_delete
kcode.kv_deletekeykvnoneRemoves key.
kcode.kv_listprefix?kva {key = value} tableLists the keys that start with exactly prefix, letter case included, with their values; no prefix lists every key.
kcode.kv_incrkey, by?kvthe new number at keyAdds by (1 when left out) to the number at key, a missing key counting as 0, in one step no other handler or session can come between, so two sessions counting never lose an update. A key holding something other than a number raises an error.
See kcode.kv_cas kcode.kv_append
kcode.kv_caskey, expected, newkvtrue when it stored new, else falseStores new (or removes the key, when new is nil) only while the key holds expected (nil: the key has no value), in one step no other handler or session can come between, so two sessions taking a lock never both get it. Numbers match by value, so 1 matches 1.0.
See kcode.kv_incr kcode.kv_append
kcode.kv_appendkey, value, max?kvhow many values the list holdsAdds value to the end of the list at key, a missing key holding none, in one step no other handler or session can come between, so two sessions logging to one key never lose an entry. With max (a whole number of at least 1) only the newest max values are kept, the oldest dropped first. A nil value, a key holding something other than a list, or a max below 1 raises an error.
See kcode.kv_cas
kcode.fetchurl | {url, method?, headers?, body?}net.http{status, body, headers}Sends an HTTP request from kcode: a GET of url, or a request with any method (POST, PUT, PATCH, DELETE, …), headers (a table of name → value) and a body (a string). Any public host is allowed, and a loopback, private or cloud-metadata host only when the net.http list in [capabilities] names it, or your own config.toml grants it under [plugin_grants.<name>] net_http: *.corp.lan covers corp.lan and every host under it. A refusal names both places. Redirects go as a browser's fetch takes them, and one to another host drops the authorization and cookie headers. A repeated header's values arrive joined by , . By default a body may be 64 MiB, a plugin may send 600 requests a minute and a request may take 120 s (plugin_host.fetch.*). A refused host raises an error with the reason. A script skill names its hosts under capabilities: in its SKILL.md; [plugin_grants] doesn't reach it.
Also in script skills
kcode.fs_readpathfs.readthe file's text, a stringReads a UTF-8 text file of the project, read-only, at most plugin_host.fs.read_max_bytes (64 MiB). A path is relative to the project folder: .., an absolute path and a link that leads out of the project are refused. An empty fs.read list reads the whole project, and one that names globs only the paths they name.
Also in script skills
See kcode.fs_list
kcode.fs_listprefix?fs.reada list of {path, is_dir} rowsLists the files and folders under prefix, matched by whole names: kcode.fs_list("notes") lists everything under notes/, subfolders and hidden entries included, and never notes-old/ or notesy.md. No prefix, or ., lists the whole project. A listing follows .gitignore, and leaves out git's own .git folder unless it lists inside it, and stops at plugin_host.fs.list_max_entries entries.
Also in script skills
See kcode.fs_read
kcode.fs_writepath, contentsfs.writenoneWrites a UTF-8 file of the project, making its folders, at most plugin_host.fs.write_max_bytes (512 MiB). Only the paths the globs of the fs.write list name are written (an empty list writes nothing) and a path inside a git folder only when a glob names .git. .., an absolute path and a link that leads out of the project are refused.
Also in script skills