Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ Then run `bun run test`, and name the version in the next `CHANGELOG.md` entry.
3. Commit, tag `vX.Y.Z`, push `main` and the tag.
4. `gh release create vX.Y.Z --title vX.Y.Z --notes-file <that section>`.

## Public contracts

The `script_create` intent and its reply (README, "From a script") are a public API that scripts and other agents depend on. Add fields only as optional ones, never rename or remove a field or change what one means, and bump `format` only for a breaking change. `carly_create` and the other intent kinds are internal and may change freely.

## Window budget

Every window-half call has a 50 ms budget for the plugin's own Lua (native calls don't count, but one call may take at most ten budgets of wall time). A call over it raises `tern: <hook> exceeded <n> ms` and Tern pauses that hook (every timer callback, say) for 5 s, doubling on repeats within 10 min, up to 5 min; `pcall` can't catch it. Keep timer passes far below it: the status and observer passes log anything over `const.WINDOW_SLOW_MS` (20 ms), and `window.luau` logs `budget` events and the status line shows *Agent Scheduler paused* while a hook is paused.
Expand Down
43 changes: 42 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ A job can also wait for something worth doing: new commits on a branch, working

- [Install](#install)
- [Create a job](#create-a-job): [Schedules](#schedules), [Only when](#only-when)
- [The manager](#the-manager): [Settings](#settings), [Carly](#carly)
- [The manager](#the-manager): [Settings](#settings), [Carly](#carly), [From a script](#from-a-script)
- [Good to know](#good-to-know)
- [Your data](#your-data)
- [Develop](#develop)
Expand Down Expand Up @@ -165,6 +165,47 @@ With each request, Agent Scheduler tells Carly to use it, rather than her own sc
> [!NOTE]
> Jobs Carly creates are active immediately with the default approval (Hands-off), and Carly can't edit or delete them; change or delete them in the manager. You get a toast and a desktop notification, and the manager marks them `by Carly`.

### From a script

Scripts, CI jobs and other agents can create a job by dropping a request file into the data folder (see [Your data](#your-data)). Tern must be running. Agent Scheduler picks the request up on its next pass, usually within 2–3 seconds, deletes it, and answers in `replies/<reply>.json`.

```sh
D="$HOME/Library/Application Support/Tern/plugin-data/tern-agent-scheduler" # macOS
# D="$HOME/.local/state/tern/plugin-data/tern-agent-scheduler" # Linux
ID=$(LC_ALL=C tr -dc 'a-z0-9' </dev/urandom | head -c 12)
F="$D/intents/$(date +%s)000-mytool-1.json"
cat >"$F.tmp" <<EOF
{ "format": 1, "kind": "script_create", "reply": "$ID", "source": "mytool",
"name": "nightly-tests", "prompt": "Run the test suite and summarise any failures.",
"when": "weekdays 2am", "folder": "~/Dev/app",
"only_when": { "new_commits": true, "branch": "main" } }
EOF
mv "$F.tmp" "$F"
for _ in $(seq 20); do [ -f "$D/replies/$ID.json" ] && break; sleep 0.5; done
cat "$D/replies/$ID.json"
```

The request is one JSON object:

| Field | |
| --- | --- |
| `format` | `1` |
| `kind` | `"script_create"` |
| `reply` | Required. Exactly 12 lowercase letters and digits, unique per request; names the reply file. |
| `prompt`, `when`, `folder` | Required. What the agent should do, the schedule as you'd type it in the form, and the project folder (a full path or `~/…`). |
| `name` | Optional. Made from the prompt when missing. |
| `role` | Optional omp role, e.g. `@smol`; `@default` when missing. |
| `quiet_ok` | Optional `true` or `false`: **Quiet when nothing to report**. |
| `only_when` | Optional object: `new_commits` (true/false), `branch`, `folders` (list or comma-separated text), `days` (`weekdays`, `weekends`, `every day` or `mon,wed`), `from` and `to` (`09:00`, `6pm`), `quiet_hours` (true runs outside those hours), `max_runs`, `max_usd`, `per` (`day` or `week`), `ask` (a question for a model) and `ask_model` (its role). |
| `source` | Optional. Your tool's name, 1–24 letters, digits, `-` or `_`; the manager marks the job `by <source>` (`by script` without one). |
| `expires` | Optional unix seconds. A request still waiting after that is refused instead of applied late. |

Any other field is refused, so a typo can't quietly make a job you didn't ask for. The job is active immediately with your default approval (**Hands-off** unless you've changed it in Settings); a request can't choose its approval. You get a toast and a desktop notification, as with Carly.

The reply is `{"format":1,"ok":true,...}` with `job_id`, `name`, `when`, `next` (text), `next_at` (unix seconds; missing for manual-only jobs), `folder`, `role`, `approval`, `only_when`, `quiet_ok` and `source`, or `{"format":1,"ok":false,"error":"..."}` with the message the form would show. Replies are deleted after about five minutes.

Name request files `<digits>-<letters and digits>-<digits>.json` (they're applied in name order), and write them under another name first and rename them into place, as above, so a half-written file is never read. Files over 16 KiB are deleted without a reply, and so is a file that still isn't valid JSON after a minute. A request without a valid `reply` is dropped without a reply.

## Good to know

- **A run waiting for your approval** is only noticed while a desktop Tern window is open.
Expand Down
1 change: 1 addition & 0 deletions lib/const.luau
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ const.INTENT_KINDS = {
ack_failed = true,
focus_manager = true,
carly_create = true,
script_create = true,
check_conditions = true,
} :: { [string]: boolean }

Expand Down
159 changes: 126 additions & 33 deletions lib/intents.luau
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
local timefmt = require("./timefmt")
-- lib/intents.luau : host side of the window -> host protocol (EN §2.3 + plan overrides 8-9).
-- Files `intents/<t_ms13>-<win8>-<seq4>.json`, applied in name order inside a time budget and removed
-- after applying. 15 allowlisted kinds (const.INTENT_KINDS); everything else (create/update/delete/
-- settings included) is dropped at once. `carly_create` makes a job directly and answers through
-- `replies/<reply>.json`.
-- after applying. 16 allowlisted kinds (const.INTENT_KINDS); everything else (create/update/delete/
-- settings included) is dropped at once. `carly_create` and `script_create` make a job directly and
-- answer through `replies/<reply>.json`. `script_create` is a public contract (README "From a script"):
-- add fields only as optional, never rename or remove one.
local conditions = require("./conditions")
local const = require("./const")
local jobs = require("./jobs")
Expand Down Expand Up @@ -54,7 +55,7 @@ local APPROVAL_LABEL: { [string]: string } = {

-- Kinds with an `expires` stamp (unix seconds) are dropped once it has passed: the window told its
-- caller they failed, so applying them later would duplicate or surprise.
local EXPIRING: { [string]: boolean } = { carly_create = true, run_now = true, check_conditions = true }
local EXPIRING: { [string]: boolean } = { carly_create = true, script_create = true, run_now = true, check_conditions = true }

local function home(): string
return ((tern :: any).getenv("HOME") :: string?) or ""
Expand All @@ -70,6 +71,13 @@ local function str(v: any, max: number): string?
return v
end

local function reply_id(v: any): string?
if type(v) == "string" and #v == 12 and v:match("^[a-z0-9]+$") then
return v
end
return nil
end

-- ---------- replies ----------

local function write_reply(id: string, tbl: { [string]: any })
Expand All @@ -93,7 +101,7 @@ local function first_error(errs: { [string]: string }): string
return "Couldn't create the job."
end

-- ---------- carly_create ----------
-- ---------- carly_create / script_create ----------

-- name derived from the prompt: first 5 words, lowercased, joined by "-", ≤ 40 chars, unique.
local function derive_name(prompt: string): string
Expand Down Expand Up @@ -123,42 +131,42 @@ local function derive_name(prompt: string): string
return name
end

local function carly_create(p: { [string]: any }, h: Handlers)
local reply = p.reply
if type(reply) ~= "string" or not reply:match("^[a-z0-9]+$") or #reply ~= 12 then
log_warn("intents: carly_create without a valid reply id")
return
-- Who asked for a job: the stored creator, a script's own name, and how the notification names it.
type Origin = { created_by: string, source: string?, who: string }

-- The creation both kinds share. f: name, prompt, when, folder, role (strings, may be ""), only_when,
-- quiet_ok (raw request values). Always answers `reply`, now or once the folder check returns.
local function create_job(reply: string, f: { [string]: any }, origin: Origin, h: Handlers)
local function failed(err: any)
log_warn("intents: " .. origin.created_by .. "_create failed", tostring(err))
pcall(reply_error, reply, "Agent Scheduler couldn't create the job.")
end
local ok, err = pcall(function()
local prompt = type(p.prompt) == "string" and p.prompt or ""
if #prompt > const.CARLY_PROMPT_MAX then
return reply_error(reply, "That prompt is too long for Carly. Use the manager.")
end
local name = str(p.name, 200) or ""
name = name:gsub("^%s+", ""):gsub("%s+$", "")
local prompt = f.prompt :: string
local name = (f.name :: string):gsub("^%s+", ""):gsub("%s+$", "")
if name == "" then
name = derive_name(prompt)
end
local role = (str(p.role, 100) or ""):gsub("^%s+", ""):gsub("%s+$", ""):gsub("^@", "")
local role = (f.role :: string):gsub("^%s+", ""):gsub("%s+$", ""):gsub("^@", "")
if role == "" then
role = "default"
end
local folder = str(p.folder, 1100) or ""
local when = str(p.when, 200) or ""
local folder = f.folder :: string
local when = f.when :: string
local now = os.time()
local input: { [string]: any } = { name = name, prompt = prompt, when = when, role = role, cwd = folder }
if p.only_when ~= nil then
local ow, owerr = conditions.from_fields(p.only_when)
if f.only_when ~= nil then
local ow, owerr = conditions.from_fields(f.only_when)
if ow == nil then
return reply_error(reply, owerr or "only_when must be a table of fields.")
end
input.only_when = ow
end
if p.quiet_ok ~= nil then
if type(p.quiet_ok) ~= "boolean" then
if f.quiet_ok ~= nil then
if type(f.quiet_ok) ~= "boolean" then
return reply_error(reply, "quiet_ok must be true or false.")
end
input.quiet_ok = p.quiet_ok
input.quiet_ok = f.quiet_ok
end
local vok, errs, norm = validate.job(input, {
jobs = jobs.list(),
Expand Down Expand Up @@ -194,7 +202,7 @@ local function carly_create(p: { [string]: any }, h: Handlers)
return reply_error(reply, string.format("No role @%s here. Roles: %s", role, table.concat(list, ", ")))
end
end
local job, cerrs = jobs.create(input, prompt, "carly", os.time())
local job, cerrs = jobs.create(input, prompt, origin.created_by, os.time(), origin.source)
if job == nil then
return reply_error(reply, first_error(cerrs or {}))
end
Expand All @@ -212,23 +220,24 @@ local function carly_create(p: { [string]: any }, h: Handlers)
local folder_label = validate.tilde(job.cwd, home())
local approval = APPROVAL_LABEL[tostring(job.approval)] or tostring(job.approval)
-- a banner works without any window open; the job is live and may run commands
pcall(notify.plain, "Agent Scheduler", string.format("Carly scheduled %s · %s · %s", tostring(job.name), approval, folder_label))
pcall(notify.plain, "Agent Scheduler", string.format("%s scheduled %s · %s · %s", origin.who, tostring(job.name), approval, folder_label))
write_reply(reply, {
ok = true,
job_id = job.id,
name = job.name,
when = jobs.describe(job),
next = nxt,
next_at = if type(st.next_run) == "number" then st.next_run else nil,
folder = folder_label,
role = "@" .. tostring(job.role),
approval = approval,
only_when = if #conditions.describe(job.conditions) > 0 then conditions.describe(job.conditions) else "always",
quiet_ok = job.quiet_ok == true,
source = origin.source,
})
end)
if not cok then
log_warn("intents: carly_create failed", tostring(cerr))
pcall(reply_error, reply, "Agent Scheduler couldn't create the job.")
failed(cerr)
end
end)
end)
Expand All @@ -237,9 +246,91 @@ local function carly_create(p: { [string]: any }, h: Handlers)
end
end)
if not ok then
log_warn("intents: carly_create failed", tostring(err))
failed(err)
end
end

-- Carly's internal message: lenient (over-long text is cut), with Carly's own prompt cap.
local function carly_create(p: { [string]: any }, h: Handlers)
local reply = reply_id(p.reply)
if reply == nil then
log_warn("intents: carly_create without a valid reply id")
return
end
local prompt = type(p.prompt) == "string" and p.prompt or ""
if #prompt > const.CARLY_PROMPT_MAX then
pcall(reply_error, reply, "That prompt is too long for Carly. Use the manager.")
return
end
create_job(reply, {
name = str(p.name, 200) or "",
prompt = prompt,
when = str(p.when, 200) or "",
folder = str(p.folder, 1100) or "",
role = str(p.role, 100) or "",
only_when = p.only_when,
quiet_ok = p.quiet_ok,
}, { created_by = "carly", who = "Carly" }, h)
end

-- The public request (README "From a script"): strict, so a misspelt or unsupported field (approval,
-- cwd, …) fails loudly instead of quietly making a job the caller didn't ask for.
local SCRIPT_FIELDS: { [string]: boolean } = {
format = true, kind = true, reply = true, expires = true, source = true,
name = true, prompt = true, when = true, folder = true, role = true, quiet_ok = true, only_when = true,
}
local SCRIPT_TEXT = { "name", "prompt", "when", "folder", "role", "source" }

local function script_problem(p: { [string]: any }): string?
local keys: { string } = {}
for k in pairs(p) do
table.insert(keys, tostring(k))
end
table.sort(keys)
for _, k in ipairs(keys) do
if not SCRIPT_FIELDS[k] then
return string.format("Unknown field “%s”.", k)
end
end
for _, k in ipairs(SCRIPT_TEXT) do
if p[k] ~= nil and type(p[k]) ~= "string" then
return k .. " must be text."
end
end
if p.expires ~= nil and type(p.expires) ~= "number" then
return "expires must be a number (unix seconds)."
end
if p.source ~= nil and validate.source(p.source) == nil then
return "source: use 1 to 24 letters, digits, - or _."
end
return nil
end

local function script_create(p: { [string]: any }, h: Handlers)
local reply = reply_id(p.reply)
if reply == nil then
log_warn("intents: script_create without a valid reply id")
return
end
local ok, problem = pcall(script_problem, p)
if not ok then
log_warn("intents: script_create failed", tostring(problem))
pcall(reply_error, reply, "Agent Scheduler couldn't create the job.")
return
elseif problem ~= nil then
pcall(reply_error, reply, problem)
return
end
local source: string? = p.source
create_job(reply, {
name = p.name or "",
prompt = p.prompt or "",
when = p.when or "",
folder = p.folder or "",
role = p.role or "",
only_when = p.only_when,
quiet_ok = p.quiet_ok,
}, { created_by = "script", source = source, who = source or "A script" }, h)
end

-- ---------- the other kinds ----------
Expand Down Expand Up @@ -347,9 +438,11 @@ local function apply(kind: string, p: { [string]: any }, h: Handlers)
h.session_ended()
elseif kind == "carly_create" then
carly_create(p, h)
elseif kind == "script_create" then
script_create(p, h)
elseif kind == "check_conditions" then
local reply = p.reply
if type(reply) ~= "string" or not reply:match("^[a-z0-9]+$") or #reply ~= 12 then
local reply = reply_id(p.reply)
if reply == nil then
log_warn("intents: check_conditions without a valid reply id")
return
end
Expand Down Expand Up @@ -413,8 +506,8 @@ function intents.drain(deadline_ms: number, h: Handlers): number
log_warn("intents: dropping intent", name, tostring(kind))
elseif EXPIRING[kind] and type(p.expires) == "number" and p.expires < os.time() then
log_warn("intents: dropping expired intent", name, kind)
local reply = p.reply
if kind == "carly_create" and type(reply) == "string" and reply:match("^[a-z0-9]+$") and #reply == 12 then
local reply = reply_id(p.reply)
if (kind == "carly_create" or kind == "script_create") and reply ~= nil then
pcall(reply_error, reply, "Timed out before Agent Scheduler could create it.")
end
else
Expand Down
8 changes: 5 additions & 3 deletions lib/jobs.luau
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,8 @@ local function materialize(job: Job, d: { [string]: any }, now: number)
if job.unattended_note == nil then job.unattended_note = true end
if job.enabled == nil then job.enabled = true end
if job.allow_home == nil then job.allow_home = false end
if job.created_by ~= "carly" then job.created_by = "user" end
if job.created_by ~= "carly" and job.created_by ~= "script" then job.created_by = "user" end
job.created_source = if job.created_by == "script" then validate.source(job.created_source) else nil
if job.created_at == nil then job.created_at = now end
if job.updated_at == nil then job.updated_at = now end
if job.tz == nil then job.tz = tz_record() end
Expand Down Expand Up @@ -615,7 +616,7 @@ local function save_both(): boolean
return ok
end

function jobs.create(input: validate.JobInput, prompt: string, created_by: string, now: number): (Job?, { [string]: string }?)
function jobs.create(input: validate.JobInput, prompt: string, created_by: string, now: number, source: string?): (Job?, { [string]: string }?)
if data_blocked() then
return nil, { name = SAVE_FAILED_COPY }
end
Expand All @@ -634,7 +635,8 @@ function jobs.create(input: validate.JobInput, prompt: string, created_by: strin
local id = ids.job_id(id_taken)
local job: Job = norm
job.id = id
job.created_by = created_by == "carly" and "carly" or "user"
job.created_by = if created_by == "carly" or created_by == "script" then created_by else "user"
job.created_source = if job.created_by == "script" then source else nil
job.created_at = now
job.updated_at = now
materialize(job, settings_tbl.defaults, now)
Expand Down
14 changes: 14 additions & 0 deletions lib/mgr_common.luau
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,20 @@ function C.short_label(label: string): string
return SHORT_LABELS[label] or label
end

-- Who made a job, for list and live rows; nil for the user's own. wide=false gives a one-glyph mark.
function C.creator_mark(job: any, wide: boolean): string?
if job.created_by == "carly" then
return if wide then "by Carly" else "✦"
elseif job.created_by == "script" then
if not wide then
return "⚙"
end
local src = job.created_source
return "by " .. (if type(src) == "string" and src ~= "" then src else "script")
end
return nil
end

function C.text(spans: Spans, key: string): Node
return C.with(ui.text(spans), { key = key })
end
Expand Down
Loading
Loading