Distributed locks and polling primitives. Each function lists its parameters, defaults and return value.
Distributed mutex primitives. Acquire a named lock from a shared store so
concurrent workflow runs serialize on a resource.
Two backends:
postgres — lease table with token-checked release/refresh. Auto-creates the lease table on first use.
dragonfly — Redis-compatible SET NX EX + Lua check-and-act.
Scope: Network
Function Description lock.acquire()Take a lock; returns a token used for subsequent calls lock.refresh()Extend the lease on an already-held lock lock.release()Drop a lock previously held under (key, token) lock.peek()Inspect the current holder without modifying state
Acquire returns an opaque token (a random UUID). The token must be
supplied to lock.refresh and lock.release; without a matching token,
neither operation will modify the lease.
The token only proves ownership at release time. It is not a monotonic
fencing token — workflows that need fencing-grade verification against a
downstream resource (e.g. preventing a stale lock holder from writing to a
shared bucket) must build that on top of this primitive.
All four functions accept these parameters for backend selection.
Parameter Type Default Description backendstring "postgres""postgres" or "dragonfly"dsnstring — Postgres DSN (postgres://...) or Redis URL (redis://...) — required tablestring "kis_locks"Postgres lease table name (ignored for dragonfly) keystring — Lock key — required for all ops
Take a distributed lock under the given key.
In addition to the common params above:
Parameter Type Default Description ttlint or string — Lease duration — required ("5m" or integer seconds) waitint or string 0How long to block-and-retry before giving up. Default 0 = fail fast ownerstring — Optional metadata stamped on the lease (visible to peek)
Field Type Description successbool Mirrors acquired acquiredbool Whether the lock was taken attemptsint Number of acquire calls before success or wait expiry keystring Echoes the requested key tokenstring Opaque ownership token (present only on success) expiresAtstring RFC3339 timestamp when the lease will expire errorstring Failure reason when success is false
log ( " someone else is deploying right now " )
// Block up to 30s for the lock
dsn: " redis://dragonfly.internal:6379/0 " ,
owner: " rotation-bot@ " + Date . now ()
Extend the lease on an already-held lock.
In addition to the common params:
Parameter Type Description tokenstring Token from the matching lock.acquire() call (required) ttlint or string New lease duration (required)
Field Type Description successbool Mirrors refreshed refreshedbool Whether the lease was extended. false when the (key, token) pair doesn’t own a live lease expiresAtstring New RFC3339 expiry on success
// Hold a lock for an extra 2 minutes during a long migration
key: " migration/2026-05-19 " ,
Drop the lock if the supplied token still owns it. Releasing with the wrong
token is a no-op — released: false, no error.
In addition to the common params:
Parameter Type Description tokenstring Token from the matching lock.acquire() call (required)
Field Type Description successbool Mirrors released releasedbool Whether the token still owned a live lease
Inspect the current holder of a key without modifying state.
Field Type Description successbool Whether the peek completed (true even when the lock isn’t held) heldbool Whether a live lease exists tokenstring Current holder’s token (when held: true) ownerstring Current holder’s owner metadata (when set on acquire) expiresAtstring RFC3339 expiry of the current lease
dsn: " redis://dragonfly.internal:6379/0 " ,
log ( " nightly report already running, owner= " + peek . owner )
// Acquire — block up to 30 seconds
let held = lock . acquire ( {
owner: " deploy- " + Date . now ()
throw " could not get deploy lock "
// Halfway through, extend the lease
Lease table is auto-created (CREATE TABLE IF NOT EXISTS) with an index
on expires_at.
Expired leases are stealable: a fresh acquire whose WHERE clause sees
expires_at < NOW() will steal the slot. There is no separate
garbage-collection job.
The lock client uses a small connection pool (5 open, 2 idle) shared
per-DSN across the process.
Table name is validated against [A-Za-z_][A-Za-z0-9_]*.
Lock value is encoded as "<token>|<owner>" so peek returns the owner
in a single GET.
release and refresh use Lua to fold the “is this still my lock?”
check and the DEL/PEXPIRE into one atomic step. The same scripts work
unchanged against real Dragonfly.
The Redis client is shared per-URL across the process.
Polling primitives — block until a runtime condition becomes true.
Today only wait.http is implemented. wait.tcp, wait.dns, wait.exec,
wait.file, and wait.db are planned and will land in this namespace
without breaking the existing API.
Scope: Network
Function Description wait.http()Poll an HTTP endpoint until the response satisfies the configured criteria
Poll a URL repeatedly until the response satisfies every configured matcher,
or the timeout elapses, or the calling context is cancelled.
Parameter Type Default Description urlstring — Target URL (required) methodstring "GET"HTTP method headersmap — Request headers — sent on every poll bodystring — Request body — reused on every poll statusint or [int] 200Acceptable HTTP status code(s) bodyMatchstring — Regex the response body must match bodyContainsstring — Substring the response body must contain headerMatchmap — Per-header regex constraints (header name → regex) intervalint or string 5sTime between polls ("5s" or integer seconds) timeoutint or string 5mTotal timeout initialDelayint or string 0Delay before the first poll insecureTLSbool falseSkip TLS certificate verification expectFailurebool falseInvert: succeed when the URL stops responding
Field Type Description successbool Whether the wait condition was met attemptsint Polls performed elapsedMsint Total elapsed milliseconds lastStatusint Status of the final poll (populated on timeout too) lastBodystring Body of the final poll lastHeadersmap Headers of the final poll errorstring Failure reason when success is false
expectFailure: true is the inverse mode. Connection errors (refused,
DNS failure, TLS rejection) count as success. A 2xx still counts as
“service is up — keep waiting.” Use it to gate on shutdown.
bodyMatch is regexp.MatchString (Go’s RE2 dialect). bodyContains
is a literal substring test — cheaper and easier to write when you don’t
need regex.
headerMatch entries combine with AND — every named header must
match its regex.
interval caps each individual request as well (the HTTP client’s
per-request timeout). A response that takes longer than the interval is
treated as a non-match for that attempt.
Last response is captured even on timeout — lastStatus, lastBody,
and lastHeaders reflect the final poll attempt, so you can introspect
why the condition never became true.
url: " http://localhost:8080/healthz " ,
throw " service never came up: " + r . error
url: " https://api.example.com/jobs/ " + jobId ,
headers: { Authorization: " Bearer " + token },
bodyContains: ' "status":"done" ' ,
log ( " job took " + r . elapsedMs + " ms ( " + r . attempts + " polls) " )
url: " https://api.example.com/version " ,
bodyMatch: " \" version \" : \" 2 \\ . \\ d+ \\ . \\ d+ \" " ,
url: " https://api.example.com/health " ,
status: [ 200 , 201 , 202 , 204 ],
url: " http://localhost:8080/healthz " ,
url: " https://api.example.com/health " ,
url: " https://api.example.com/state " ,
bodyContains: ' "ready":true ' ,
log ( " gave up after " + r . attempts + " polls; last status= " + r . lastStatus )
log ( " last body: " + r . lastBody )
url: " https://api.example.com/check " ,
body: ' {"region":"us-east-1"} ' ,
headers: { " Content-Type " : " application/json " },
bodyContains: ' "ok":true ' ,
Scheduled job management functions. Manages recurring and one-time jobs with YAML-based storage and OS scheduler integration. Cross-platform support for crontab (Linux), launchd (macOS), and Task Scheduler (Windows).
Scope: System
Function Description cron.add()Add a recurring scheduled job cron.once()Schedule a one-time job cron.remove()Remove a job cron.list()List all managed jobs cron.show()Show details of a specific job cron.exec()Execute a job in foreground cron.run()Run a job in background cron.logs()View job log output cron.history()View job execution history cron.sync()Sync between YAML store and OS scheduler
Add a recurring scheduled job.
Parameter Type Default Description namestring — Job name (required) commandstring — Command to execute (required) schedulestring — Schedule expression (required) dirstring — Working directory shellstring /bin/shShell to use envmap — Environment variables timeoutstring — Job timeout (30m, 1h) overlapstring — Concurrent execution: skip, queue, allow enabledbool trueWhether job is active
Schedule accepts human-friendly expressions (daily at 2am, every 5 minutes, weekly on monday at 9am) or raw cron syntax (cron */5 * * * *).
Field Type Description successbool Whether the job was added jobmap Job details (name, schedule, cron, command, enabled, etc.) errorstring Error message if failed
// Add a daily backup job
command: " /opt/scripts/backup.sh " ,
schedule: " daily at 2am " ,
env: { BACKUP_DIR: " /mnt/backups " }
log ( " Job created: " + result . job . name )
// Add with raw cron expression
command: " curl -sf http://localhost:8080/health " ,
schedule: " cron */5 * * * * " ,
command: " /opt/scripts/report.sh " ,
schedule: " weekly on monday at 9am " ,
Schedule a one-time job execution.
Parameter Type Default Description namestring — Job name (required) commandstring — Command to execute (required) timestring — When to run: now, in 5 minutes, today at 3pm (required) dirstring — Working directory shellstring /bin/shShell to use envmap — Environment variables timeoutstring — Job timeout
Field Type Description successbool Whether the job was scheduled jobmap Job details errorstring Error message if failed
command: " /opt/scripts/migrate.sh " ,
command: " /opt/scripts/deploy.sh --version v2.0.0 " ,
// Schedule in relative time
command: " /opt/scripts/cleanup.sh " ,
Remove a scheduled job.
Parameter Type Default Description Input string or map — Job name string, or map with name key (required)
Field Type Description successbool Whether the job was removed errorstring Error message if failed
cron . remove ( " health-check " )
cron . remove ({ name: " old-backup " })
List all managed jobs.
Parameter Type Default Description Input nil or map — Optional map with data_dir
Field Type Description successbool Whether the listing succeeded jobsarray Array of job objects errorstring Error message if failed
Each job object contains:
Field Type Description namestring Job name schedulestring Human-friendly schedule cronstring Cron expression commandstring Command to execute enabledbool Whether the job is active createdstring Creation timestamp (ISO 8601) updatedstring Last update timestamp (ISO 8601)
for ( let job of result . jobs ) {
let status = job . enabled ? " enabled " : " disabled "
log ( job . name + " [ " + status + " ] — " + job . schedule )
let enabled = result . jobs . filter ( j => j . enabled ) . length
log ( " Enabled jobs: " + enabled + " / " + result . jobs . length )
Show details of a specific job.
Parameter Type Default Description Input string or map — Job name string, or map with name key (required)
Field Type Description successbool Whether the lookup succeeded jobmap Full job details errorstring Error message if failed
let result = cron . show ( " daily-backup " )
log ( " Schedule: " + result . job . schedule )
log ( " Cron: " + result . job . cron )
log ( " Command: " + result . job . command )
log ( " Enabled: " + result . job . enabled )
let result = cron . show ( { name: " health-check " } )
log ( " Timeout: " + result . job . timeout )
Execute a job immediately in the foreground. Waits for completion and returns output.
Parameter Type Default Description Input string or map — Job name string, or map with name key (required)
Field Type Description successbool Whether execution succeeded outputstring Command output exit_codeint Process exit code errorstring Error message if failed
let result = cron . exec ( " daily-backup " )
log ( " Output: " + result . output )
log ( " Exit code: " + result . exit_code )
log ( " Failed: " + result . error )
Run a job in the background. Returns immediately without waiting for completion.
Parameter Type Default Description Input string or map — Job name string, or map with name key (required)
Field Type Description successbool Whether the job was started outputstring Startup output errorstring Error message if failed
let result = cron . run ( " daily-backup " )
log ( " Job started in background " )
View job log output.
Parameter Type Default Description Input string or map — Job name string, or map with options (required) namestring — Job name (required) linesint 50Number of log lines to return
Field Type Description successbool Whether the logs were retrieved logsstring Log content errorstring Error message if failed
// View last 50 lines (default)
let result = cron . logs ( " daily-backup " )
let result = cron . logs ( { name: " daily-backup " , lines: 100 } )
View job execution history with timestamps, duration, and exit codes.
Parameter Type Default Description Input string or map — Job name string, or map with options (required) namestring — Job name (required) linesint 50Number of history entries
Field Type Description successbool Whether the history was retrieved historyarray Array of history entries errorstring Error message if failed
Each history entry contains:
Field Type Description jobstring Job name startedstring Start timestamp (ISO 8601) finishedstring Finish timestamp (ISO 8601) durationstring Execution duration exit_codeint Process exit code triggerstring What triggered the execution
let result = cron . history ( " daily-backup " )
for ( let entry of result . history ) {
let status = entry . exit_code === 0 ? " OK " : " FAILED "
log ( entry . started + " — " + entry . duration + " — " + status )
let result = cron . history ( { name: " health-check " , lines: 20 } )
let failures = result . history . filter ( e => e . exit_code !== 0 )
log ( " Failures: " + failures . length + " / " + result . history . length )
Sync between the YAML job store and the OS scheduler (crontab, launchd, or Task Scheduler).
Parameter Type Default Description directionstring "both"Sync direction: to-os, from-os, both dry_runbool falsePreview changes without applying
Field Type Description successbool Whether the sync succeeded changesarray Array of change objects errorstring Error message if failed
Each change object contains:
Field Type Description actionstring Change action (add, remove, update) namestring Job name detailstring Description of the change
// Sync YAML to OS scheduler
let result = cron . sync ( { direction: " to-os " } )
for ( let change of result . changes ) {
log ( change . action + " : " + change . name + " — " + change . detail )
// Preview changes (dry run)
let result = cron . sync ( { direction: " both " , dry_run: true } )
log ( " Pending changes: " + result . changes . length )
for ( let change of result . changes ) {
log ( " [ " + change . action + " ] " + change . name )
cron . sync ({ direction: " from-os " })
// Complete job lifecycle: create, verify, execute, check logs, clean up
let jobName = " nightly-backup "
command: " /opt/scripts/backup.sh --full " ,
schedule: " daily at 2am " ,
BACKUP_TARGET: " /mnt/backups " ,
log ( " Created job: " + added . job . name )
let details = cron . show ( jobName )
log ( " Schedule: " + details . job . schedule )
log ( " Cron expression: " + details . job . cron )
// Execute immediately to test
let execResult = cron . exec ( jobName )
log ( " Test run exit code: " + execResult . exit_code )
let logs = cron . logs ( { name: jobName , lines: 20 } )
log ( " Output: " + logs . logs )
let syncResult = cron . sync ( { direction: " to-os " } )
log ( " Synced " + syncResult . changes . length + " changes to OS " )
let allJobs = cron . list ()
log ( " Total managed jobs: " + allJobs . jobs . length )
TCP/UDP port management functions.
Scope: System
Function Description port.check()Check if a port is free port.find()Find the first free port in a range port.list()List processes using a port port.kill()Kill all processes on a port
Check if a TCP/UDP port is free. Uses fuser on Linux.
Parameter Type Default Description Input int or map — Port number, or map with options (required) portint — Target port number (required) protocolstring "tcp"Protocol: "tcp" or "udp"
Field Type Description successbool Whether the check completed freebool Whether the port is free errorstring Error message if failed
// Simple check with port number
let result = port . check ( 8080 )
log ( " Port 8080 is available " )
log ( " Port 8080 is in use " )
let result = port . check ( { port: 5353 , protocol: " udp " } )
log ( " UDP 5353 free: " + result . free )
Find the first free port in a range. Scans from startport to endport in steps of increment, skipping ports below minport.
Parameter Type Default Description startportint 3000Range start endportint 65000Range end incrementint 1000Step size minportint 10000Skip ports below this value protocolstring "tcp"Protocol: "tcp" or "udp"
Field Type Description successbool Whether a free port was found portint The free port number errorstring Error message if failed
// Find free port with defaults
let result = port . find ( {} )
log ( " Free port: " + result . port )
// Find in a specific range
log ( " Free port: " + result . port )
// Find with minimum port
log ( " Found port: " + result . port )
log ( " No free port found in range " )
List processes using a specific port.
Parameter Type Default Description Input int or map — Port number, or map with options (required) portint — Target port number (required) protocolstring "tcp"Protocol: "tcp" or "udp"
Field Type Description successbool Whether the listing succeeded processesarray Array of process objects errorstring Error message if failed
Each process object contains:
Field Type Description pidstring Process ID userstring Process owner commandstring Command name
// List processes on port 8080
let result = port . list ( 8080 )
for ( let p of result . processes ) {
log ( p . pid + " " + p . user + " " + p . command )
let result = port . list ( { port: 53 , protocol: " udp " } )
if ( result . processes . length === 0 ) {
log ( " No processes on UDP port 53 " )
log ( " Found " + result . processes . length + " processes " )
Kill all processes using a port. Sends the specified signal to all processes.
Parameter Type Default Description Input int or map — Port number, or map with options (required) portint — Target port number (required) protocolstring "tcp"Protocol: "tcp" or "udp" signalstring "KILL"Signal to send (KILL, TERM, HUP, etc.)
Field Type Description successbool Whether the kill succeeded freebool Whether the port is now free errorstring Error message if failed
// Kill with default signal (KILL)
let result = port . kill ( 8080 )
log ( " Port free: " + result . free )
port . kill ({ port: 8080 , signal: " TERM " })
// Kill processes on UDP port
port . kill ({ port: 5353 , protocol: " udp " , signal: " TERM " })
// Port management workflow: check, list, kill, verify
// Check if port is in use
let check = port . check ( targetPort )
let procs = port . list ( targetPort )
log ( " Port " + targetPort + " is in use by: " )
for ( let p of procs . processes ) {
log ( " PID " + p . pid + " : " + p . command + " ( " + p . user + " ) " )
port . kill ({ port: targetPort , signal: " TERM " })
let verify = port . check ( targetPort )
log ( " Port " + targetPort + " is now free " )
log ( " Port " + targetPort + " is available " )
OS user management functions.
Scope: System
Function Description user.check()Check if an OS user exists user.create()Create a new OS user user.delete()Delete an OS user user.modify()Modify user properties user.passwd()Set or change a user password
Check if an OS user exists. Returns user details (UID, GID, home directory) when found.
Parameter Type Default Description Input string or map — Username string, or map with username key (required)
Field Type Description successbool Whether the check completed existsbool Whether the user exists uidstring User’s numeric UID gidstring User’s numeric GID homedirstring User’s home directory errorstring Error message if failed
// Check with username string
let result = user . check ( " deploybot " )
log ( " User found — UID: " + result . uid + " , Home: " + result . homedir )
log ( " User does not exist " )
let result = user . check ( { username: " appuser " } )
log ( " Exists: " + result . exists )
Create a new OS user. Uses useradd on Linux.
Parameter Type Default Description Input string or map — Username string, or map with options (required) usernamestring — Target username (required) groupnamestring — Primary group name shellstring /bin/bashLogin shell homestring — Home directory path groupsarray — Supplementary groups createhomebool trueCreate home directory systembool falseCreate as system account
Field Type Description successbool Whether the user was created errorstring Error message if failed
// Simple create with username string
// Create with primary group and supplementary groups
groups: [ " docker " , " sudo " ],
// Create a system account
// Create with custom home directory
Delete an OS user. Uses userdel on Linux.
Parameter Type Default Description Input string or map — Username string, or map with options (required) usernamestring — Target username (required) removehomebool falseRemove home directory on deletion
Field Type Description successbool Whether the user was deleted errorstring Error message if failed
// Delete and remove home directory
user . delete ({ username: " olduser " , removehome: true })
Modify OS user properties. Uses usermod on Linux.
Parameter Type Default Description usernamestring — Target username (required) groupnamestring — New primary group shellstring — New login shell homestring — New home directory groupsarray — New supplementary groups
Field Type Description successbool Whether the modification succeeded errorstring Error message if failed
// Add user to more groups
groups: [ " docker " , " sudo " , " adm " ]
// Change primary group and home
Set or change an OS user’s password. Uses chpasswd on Linux.
Parameter Type Default Description usernamestring — Target username (required) passwordstring — New password in plain text (required)
Field Type Description successbool Whether the password was set errorstring Error message if failed
password: " secure-password-123 "
// Complete user provisioning workflow
let username = " deploybot "
// Check if user already exists
let result = user . check ( username )
// Create user with groups
let created = user . create ( {
groups: [ " docker " , " sudo " ] ,
password: " initial-password "
log ( " User " + username + " created successfully " )
log ( " User " + username + " already exists (UID: " + result . uid + " ) " )
groups: [ " docker " , " sudo " , " adm " ]