Snu agent api

From arnoudkooi/sn-scriptsync · View interactive version

Snu agent api is an AI agent skill from the GitHub repository arnoudkooi/sn-scriptsync. SN ScriptSync HTTP/file Agent API: endpoint discovery, auth, the full error-code table, and the complete command catalog (query_records, get_record, update_record, create_records / update_records for many rows, create_artifact, create_application, analyze_artifact_type, rest_request, screenshots, et

How to use this skill

Skill file

<!-- SN-SCRIPTSYNC:SKILL instructionsSchemaVersion=39 -->

SN ScriptSync — Agent API

Full reference for the SN ScriptSync Agent API and every command except the live-form g_form bridge (see the snu-form-automation skill) and the browser debugger (see the snu-browser-debug skill).

SN ScriptSync - Agent API

The Agent API lets AI assistants drive the extension: sync files, create/update records, query ServiceNow, take screenshots, and more. Two transports are available. Prefer the HTTP transport; the file transport is kept for backward compatibility.

The browser helper tab is still required. Both transports only change the agent <-> extension hop. Anything that touches ServiceNow (record reads/writes, queries, screenshots) still round-trips through the SN Utils helper tab over WebSocket. Keep a helper tab open (run /token in a browser session) or commands return E_BROWSER_DISCONNECTED.

Transport 1: HTTP (recommended, event-driven)

When the extension is running it spins up a local HTTP server bound to 127.0.0.1, preferring the fixed port 1977 (ephemeral fallback if taken). The actual port and auth token are published to two port files — ~/.sn-scriptsync/agent-port.json (well-known, discoverable from any directory; written only while the connected browser has an active SN Utils Pro/Trial/Enterprise license) and <workspace>/.vscode/sn-agent-port.json (always written — workspace agent workflows are free):

{
  "port": 1977,
  "token": "4f9a...hex...",
  "pid": 68861,
  "apiVersion": 6,
  "startedAt": 1734000000000
}

Discovering the endpoint

# Unix / macOS — global file works from any cwd; older versions only write the workspace file
PORT=$(jq -r .port ~/.sn-scriptsync/agent-port.json 2>/dev/null || jq -r .port .vscode/sn-agent-port.json)
TOKEN=$(jq -r .token ~/.sn-scriptsync/agent-port.json 2>/dev/null || jq -r .token .vscode/sn-agent-port.json)
# Windows PowerShell
$cfg = Get-Content "$HOME/.sn-scriptsync/agent-port.json" | ConvertFrom-Json
$PORT  = $cfg.port
$TOKEN = $cfg.token

Required discovery algorithm (do this every session)

Port files can be stale (leftover from a crash; the workspace copy may even be synced

by iCloud/OneDrive/git from another machine), so never trust one blindly and never cache

the port/token. Each session:

  1. Read port, token, and pid from ~/.sn-scriptsync/agent-port.json, falling back to

<workspace>/.vscode/sn-agent-port.json (older versions write only the workspace file).

  1. Call GET http://127.0.0.1:<port>/api/health.
  2. Trust the endpoint only if all hold:
  1. If any check fails (no file, connection refused, pid mismatch, version mismatch),

the HTTP server is not usable here — fall back to the file transport below.

  1. Detect available commands from health.commands[] rather than hard-coding the list;

it changes between versions.

Health check (no auth)

curl -s http://127.0.0.1:$PORT/api/health
# → { "status": "success", "apiVersion": 6, "commands": [...], "pid": 68861 }

The extension deletes both port files when the server stops, but a crash or a sync

conflict can leave a stale file behind — which is exactly why the pid cross-check

in step 3 is mandatory before sending real commands.

Self-describing docs (no auth)

The running server serves its own documentation, so instructions can never drift from

the installed version: GET /api/instructions (connect guide + core instructions),

GET /api/skills (skill index), GET /api/skills/<name> (full skill markdown). If you

were handed only the endpoint — no workspace, no files — start there.

Sending a command

Every authenticated request is POST /api with a JSON body. Provide an X-Agent-Token header.

curl -s -X POST http://127.0.0.1:$PORT/api \
  -H "Content-Type: application/json" \
  -H "X-Agent-Token: $TOKEN" \
  -d '{
        "command": "check_connection",
        "instance": "dev12345"
      }'

Response:

{
  "id": "http_1734000001234_a1b2c3",
  "command": "check_connection",
  "status": "success",
  "result": { "ready": true, "appName": "Cursor" },
  "timestamp": 1734000001235
}

If id is omitted, the server generates one. Errors return a JSON body with status: "error" and a structured code:

{ "status": "error", "code": "E_BROWSER_DISCONNECTED", "error": "No browser helper tab is connected." }

HTTP status codes map to codes:

| Code | HTTP | Meaning |

|------|------|---------|

| E_INVALID_PARAMS / E_INVALID_REQUEST / E_CONFIRM_REQUIRED | 400 | Malformed request, or a destructive command called without confirm:true |

| E_UNAUTHORIZED | 401 | Missing/invalid X-Agent-Token |

| E_UNKNOWN_COMMAND / E_NOT_FOUND | 404 | No such command, or the target record doesn't exist |

| E_REFERENCE_INTEGRITY | 409 | Write/delete blocked by a reference or data-integrity constraint |

| E_INSTANCE_REQUIRED / E_INSTANCE_NOT_FOUND | 422 | Instance not resolvable |

| E_VERIFY_FAILED | 422 | Standalone update_record was acknowledged but persistence could not be verified. Inspect details.reason and the saved state before retrying; the write may already have taken effect |

| E_DISCOVERY_FAILED | 422 | pull_scope could not pull any table, because the instance dictionary or the scope's record list could not be read completely. details holds the full report (skipped tables, warnings). Pull single tables with pull_records meanwhile |

| E_DISABLED | 423 | Feature disabled via settings (e.g. deletes, background scripts) |

| E_PAUSED | 423 | The user paused agent access in the ScriptSync helper tab. Stop and tell the user — do not retry until they press Resume agents there |

| E_PARTIAL_FAILURE | 207 | Batch partially succeeded — inspect per-item results |

| E_REVIEW_PENDING | 202 | The command needs human approval in the helper tab Review Queue. Tell the user to approve it in the SN Utils ScriptSync helper tab in their browser, then call get_review_result with the reviewId from details to collect the outcome |

| E_USER_REJECTED | 403 | The developer rejected the command in the Review Queue — do not retry without asking the user |

| E_COMMAND_FAILED | 500 | The command was accepted (and, when applicable, approved) but failed during execution. Inspect details.status, details.detail, and details.response; this is not a user rejection |

| E_INTERNAL | 500 | Unexpected error |

| E_ACL / E_TOKEN_EXPIRED / E_SCREENSHOT_PERMISSION | 502 | ServiceNow rejected the request, or a tab needs a one-time capture grant (click the SN Utils icon on it, then retry) |

| E_SERVER_NOT_RUNNING / E_BROWSER_DISCONNECTED | 503 | Can't reach ServiceNow |

| E_TIMEOUT | 504 | Round-trip exceeded deadline |

Resolving `E_INSTANCE_REQUIRED` (multiple instances)

When a command returns E_INSTANCE_REQUIRED, you didn't pass "instance" and

the bridge could not select a single safe target. details.knownInstances lists

remembered workspace folders; details.connectedInstances lists the subset

observed on the current helper connection. A folder is not proof of a live

session. auth_status automatically selects the target only when exactly one

known folder matches a helper-observed instance.

If the error says Multiple known workspace instances found, do not describe

those folders as active connections. If it says `Multiple helper-connected

instances found`, ask for a target (especially for a write) or use the roster

and freshness guidance below.

Use freshness as a default pick, not an exclusivity test. The extension

rewrites <instance>/_settings.json (refreshing g_ck) every time it relays for

that instance, so the **most recently modified _settings.json is the

most-recently-active session**.

The fastest path — and the one to prefer — is the one-shot list_instances

command. It's purely local (no browser round-trip, never returns

E_INSTANCE_REQUIRED) and returns the whole roster, each url, a freshest-first

ranking, and a suggested defaultInstance:

  1. Call list_instances. If defaultInstance is set (exactly one instance was

recently active), retry your command with "instance": defaultInstance.

  1. If needsConfirmation is true (none recent, or two-plus recent — e.g.

ven08329 + ven08331), or the operation is a write / destructive action,

confirm the target with the user instead of guessing.

  1. Optionally confirm the chosen instance's bridge actually responds with a cheap

get_instance_info (check recentlyActive / lastActiveAgeMs) or

query_records round-trip before committing — connected is bridge-level and

is true for every instance whenever the helper tab is up, so it doesn't

disambiguate.

If list_instances isn't available (older extension), fall back to reading the

<instance>/_settings.json mtimes yourself and applying the same rule. Once

resolved, reuse that instance for the rest of the session.

Transport: HTTP only

The legacy file-based transport ({instance_folder}/agent/requests/*.json) was removed in 4.8.0. Every agent flow uses the HTTP Agent API above; if a request file is dropped in the workspace nothing will pick it up.

Commands

`check_connection` ⚡ (CALL THIS FIRST)

Verify WebSocket server is running and browser helper tab is connected. Always call this before any other operations.

Request:

{ "id": "0", "command": "check_connection" }

Response (ready):

{
  "status": "success",
  "result": {
    "ready": true,
    "serverRunning": true,
    "browserConnected": true,
    "message": "Connected and ready",
    "helper": { "debuggerAvailable": false, "tier": "pro", "proFeatures": true }
  }
}

helper tells you which SN Utils build is connected. debuggerAvailable is true only on the SN Utils Debug edition; most users run the regular build. You don't need this to take screenshots (take_screenshot auto-routes to the best available path), but it tells you what else this session can do:

Response (server not running):

{
  "status": "error",
  "error": "WebSocket server not running. Click sn-scriptsync in VS Code status bar to start.",
  "result": {
    "ready": false,
    "serverRunning": false,
    "browserConnected": false,
    "message": "WebSocket server not running"
  }
}

Response (no browser):

{
  "status": "error",
  "error": "No browser connection. Open SN Utils helper tab via /token command in ServiceNow.",
  "result": {
    "ready": false,
    "serverRunning": true,
    "browserConnected": false,
    "message": "No browser connected - open helper tab with /token"
  }
}

`get_capabilities` ⚡ (preflight Pro / debugger / security gates)

Ask the connected SN Utils helper tab what it can do right now — the Agent API version, the license tier, whether the Chrome DevTools Protocol browser debugger (network/console capture, full-page screenshots, native dialog handling) is usable, which protocol capabilities the helper supports (two-phase command review, per-instance security gates), and the per-instance instanceGates snapshots. Call this once up front so you can preflight E_DISABLED instead of discovering it mid-operation, and before reaching for the snu-browser-debug skill instead of firing a CDP command and parsing the error.

Requires a connected helper tab (E_BROWSER_DISCONNECTED otherwise — run check_connection first).

Request:

{ "id": "cap_1", "command": "get_capabilities" }

Response (v8 helper with per-instance gates):

{
  "status": "success",
  "result": {
    "apiVersion": 8,
    "tier": "pro",
    "proFeatures": true,
    "cdp": { "available": true, "reason": null },
    "capabilities": { "protocolVersion": 1, "commandReview": 1, "instanceSecurityGates": 1 },
    "instanceGates": {
      "https://example.service-now.com": {
        "revision": 3,
        "gates": {
          "backgroundScripts": "approve",
          "deleteRecords": "off",
          "createArtifacts": "auto",
          "browserDebugger": "off",
          "restRequest": "auto"
        }
      }
    }
  }
}

Response (older SN Utils build — no review protocol):

{
  "status": "success",
  "result": {
    "apiVersion": 8,
    "tier": "pro",
    "proFeatures": true,
    "cdp": { "available": false, "reason": "E_CDP_UNAVAILABLE" },
    "capabilities": { "protocolVersion": 1 },
    "instanceGates": {}
  }
}

`get_review_result` (collect a human-review outcome)

Guarded commands (background scripts, deletes, some UI actions) whose per-instance gate is set to Approve don't execute immediately: the command returns E_REVIEW_PENDING right away with a reviewId, and the actual request waits in the SN Utils helper tab Review Queue for the developer to approve or reject (5-minute window). The helper tab announces the pending review itself (sound, favicon flash, Review Queue badge).

When you receive E_REVIEW_PENDING: tell the user to approve the request in the SN Utils ScriptSync helper tab in their browser, then call this command to collect the outcome. Long-polls up to waitSeconds (default 30, max 55) per call; poll again while it keeps returning E_REVIEW_PENDING.

Request:

{ "id": "revres_1", "command": "get_review_result", "params": { "reviewId": "rev_1786...._ab12cd", "waitSeconds": 30 } }

Response (approved & executed): the original command's result, e.g. for run_background_script:

{ "status": "success", "result": { "reviewId": "rev_....", "command": "run_background_script", "output": "*** Script: ..." } }

Errors:

Prefer this two-phase flow. If you genuinely need the old blocking behavior (the original call holding open until the decision), pass "awaitReview": true in the original command's params — but note most HTTP clients time out long before the 5-minute window.

`get_batch_result`

Collect the outcome of a create_records / update_records batch by its batchId: after the call returned E_TIMEOUT, after a review was approved, or after the connection dropped. Call it before retrying any row.

Requires: browser helper tab connected, in the browser profile that ran the batch. Results are kept there for 24 hours.

Request:

{ "id": "batch_1", "command": "get_batch_result", "instance": "dev12345", "params": { "batchId": "bat_lzx1y2_a1b2c3d4" } }

Response: the same shape as the batch command. While the helper is still writing, status is success with running: true and the rows answered so far; call again. Once finished, the same success or error mapping as the original call (E_PARTIAL_FAILURE with every row in details, and so on). A batch whose helper tab closed mid-run comes back with interrupted: true, and the row it was sending is unknown.

Errors:

`list_instances`

List every instance in the workspace with its URL and per-instance activity

freshness, plus a suggested default. Purely local — it reads the

*/​_settings.json files directly, so it needs no browser helper tab and never

returns E_INSTANCE_REQUIRED. Use it as the first step when you don't yet know

which instance to target.

instances is sorted freshest-first (lastActiveAgeMs ascending; never-active

folders last). recentlyActive means the instance's _settings.json was

rewritten within ~10h — the extension refreshes that file (and g_ck) whenever

the helper tab relays for that instance, so it's a freshness proxy, not proof of

a live tab. defaultInstance is set only when exactly one instance is

recently active; when needsConfirmation is true (none recent, or two-plus

recent) pick with the user before any write. connected is bridge-level (the one

helper tab relays for every instance), not per-instance.

Request:

{ "id": "1", "command": "list_instances" }

Response:

{
  "result": {
    "instances": [
      { "name": "ven08329", "url": "https://ven08329.service-now.com", "recentlyActive": true, "lastActiveAgeMs": 425000, "hasSettings": true },
      { "name": "ven08331", "url": "https://ven08331.service-now.com", "recentlyActive": true, "lastActiveAgeMs": 980000, "hasSettings": true },
      { "name": "empakooi", "url": "https://empakooi.service-now.com", "recentlyActive": false, "lastActiveAgeMs": 10500000000, "hasSettings": true }
    ],
    "count": 3,
    "connected": true,
    "defaultInstance": null,
    "needsConfirmation": true
  }
}

`get_instance_info`

Get instance connection info, including per-instance activity freshness.

Pass "instance" to inspect a specific candidate (useful for disambiguating

E_INSTANCE_REQUIRED). connected is bridge-level — it is true for every

instance whenever the WS server is up with the helper tab connected, because the

single helper tab relays for every instance the browser has a session for. Use

recentlyActive / lastActiveAgeMs (derived from the _settings.json mtime) to

tell which instance is the most-recently-active session.

Request:

{ "id": "2", "command": "get_instance_info", "instance": "ven08329" }

Response:

{
  "result": {
    "instanceName": "ven08329",
    "hasSettings": true,
    "connected": true,
    "recentlyActive": true,
    "lastActiveAgeMs": 425000
  }
}

`get_sync_status`

Get current sync queue status.

Request:

{ "id": "1", "command": "get_sync_status" }

Response:

{
  "result": {
    "serverRunning": true,
    "pendingFiles": ["/path/to/file.js"],
    "pendingCount": 1,
    "syncingFiles": ["/path/to/other.js"],
    "syncingCount": 1,
    "isPaused": false
  }
}

syncingFiles were sent to the instance and wait for the helper tab's confirmation; sync_now never sends them twice. A file whose save failed stays in pendingFiles, held for the user, with the reason in the Pending Saves panel.

`sync_now` ⚡

Send eligible pending files from the VS Code workspace queue. Inspect get_sync_status first and use this only when all eligible files belong to the authorized task: it does not filter by instance or file. The standalone host does not provide this queue; use the typed record-write commands there.

synced: true means the files were sent, not that their content was verified. Wait until the intended files leave both pendingFiles and syncingFiles, then read their records with get_record and compare the changed fields. An empty queue or count: 0 does not prove your edits reached the instance.

When sn-scriptsync.agentApi.reviewWrites is enabled, the result has synced: false and blocked: true: tell the user to approve the intended files in VS Code Pending Saves (per-file ✓). Saves held for the user after Save All, auto save or refactoring cannot be flushed by an agent either. Do not bypass these holds using a direct write.

Request:

{ "id": "2", "command": "sync_now" }

Response (when files pending):

{
  "result": {
    "synced": true,
    "message": "Synced 3 file(s) immediately",
    "count": 3,
    "files": ["/path/to/file1.js", "/path/to/file2.js", "/path/to/file3.js"]
  }
}

Response (when no files pending):

{
  "result": {
    "synced": false,
    "message": "No pending files to sync",
    "count": 0
  }
}

`get_last_error`

Get the last error that occurred. Errors are automatically written to _last_error.json in the folder of the instance that reported them, and that instance's pending Agent requests are failed when ServiceNow returns an error. Other instance folders in the workspace are untouched.

Request:

{ "id": "err", "command": "get_last_error" }

Response (when error exists):

{
  "result": {
    "hasError": true,
    "isRecent": true,
    "error": "ACL Error, try changing scope in the browser",
    "time": "2024-12-07T12:30:45.123Z",
    "timestamp": 1733567445123,
    "details": { "message": "...", "detail": "..." },
    "instance": { "name": "dev221527", "url": "https://dev221527.service-now.com" }
  }
}

Response (no error):

{
  "result": {
    "hasError": false,
    "message": "No errors recorded"
  }
}

`clear_last_error`

Clear the last error file.

Request:

{ "id": "clr", "command": "clear_last_error" }

Response:

{
  "result": {
    "cleared": true,
    "message": "Error cleared"
  }
}

`update_record`

Update a single field on an existing record. Fire-and-forget (the extension sends the update through the helper tab; success is reported back asynchronously).

Use field plus content. A fields object belongs to update_record_batch; it is not accepted as a substitute for these parameters.

Requires: browser helper tab connected.

Gating: updateRecords (sn-scriptsync.updateRecords.enabled in VS Code, SNU_ALLOW_UPDATE_RECORDS in the standalone snu host, or the per-instance Update Records grant in the SN Utils helper tab) — on by default. Where nothing sets it, it follows createArtifacts: a host or instance that may not create records may not overwrite them either.

Request:

{
  "id": "upd_1",
  "command": "update_record",
  "instance": "dev12345",
  "params": {
    "table": "sys_script_include",
    "sys_id": "abc123def456...",
    "field": "script",
    "content": "gs.info('hello from the agent');"
  }
}

Response (success):

{
  "id": "upd_1",
  "command": "update_record",
  "status": "success",
  "result": {
    "success": true,
    "message": "Update sent for sys_script_include/abc123def456...",
    "table": "sys_script_include",
    "sys_id": "abc123def456...",
    "field": "script"
  }
}

Synchronous confirmation: add "await": true to write via the Table API and read the value back. The response then includes awaited: true, the persisted value, and a warnings[] array flagging any field that came back empty (e.g. silently dropped by an ACL/read-only/business rule).

{ "id": "upd_2", "command": "update_record", "params": { "table": "sys_script_include", "sys_id": "abc...", "field": "active", "content": "false", "await": true } }

Review mode: when sn-scriptsync.agentApi.reviewWrites is on (default off), this write is not sent. It is parked in the VS Code "Pending Saves" queue and the response is { "staged": true, "reviewId": "...", "message": "..." }. The user reviews it and approves it with Sync Now (or discards it); await is ignored while staged. Treat a staged: true response as "queued for human approval", not "applied".

Standalone persistence verification: the standalone host waits for the PATCH, then separately reads the field using raw stored values and compares it to content, even when await is omitted. A match returns updated: true, awaited: true, verified: true, persisted: { "<field>": <saved value> } and an empty warnings list. Empty content remains a deliberate clear; script whitespace is significant.

A mismatch, unreadable field or failed read returns E_VERIFY_FAILED (HTTP 422) with details.writeAcknowledged: true, verified: false and a reason (value_mismatch, field_unreadable or read_failed). A failed read also includes causeCode. The write may already have taken effect: inspect the record and any ACL/business rule before retrying. Journal fields such as work_notes must be checked through the new sys_journal_field entry, not by equality against the parent record field; never repeat a journal write just because that comparison failed.

Do not verify twice: a successful verified: true result with matching persisted content already completes persistence verification. No extra get_record is needed. Only on hosts or save results without that confirmation, call get_record and compare the content before reporting it saved. A PATCH success or increased sys_mod_count alone is insufficient. Collect any pending approval before checking for the resulting change.

Errors:

`update_record_batch`

Update multiple fields on the same record in one round-trip. Preferred for multi-file artifacts (widgets, UI pages) where you'd otherwise send many update_record calls.

Requires: browser helper tab connected.

Gating: updateRecords (sn-scriptsync.updateRecords.enabled in VS Code, SNU_ALLOW_UPDATE_RECORDS in the standalone snu host, or the per-instance Update Records grant in the SN Utils helper tab) — on by default. Where nothing sets it, it follows createArtifacts: a host or instance that may not create records may not overwrite them either.

Request:

{
  "id": "upd_batch_1",
  "command": "update_record_batch",
  "instance": "dev12345",
  "params": {
    "table": "sp_widget",
    "sys_id": "abc123def456...",
    "fields": {
      "script":        "data.hello = 'world';",
      "client_script": "function($scope){ /* ... */ }",
      "css":           ".c1 { color: red; }"
    }
  }
}

Response (success):

{
  "id": "upd_batch_1",
  "command": "update_record_batch",
  "status": "success",
  "result": {
    "success": true,
    "message": "Updated 3 field(s) on sp_widget/abc123def456...",
    "table": "sp_widget",
    "sys_id": "abc123def456...",
    "fields": ["script", "client_script", "css"]
  }
}

Synchronous confirmation: add "await": true to write via the Table API and read the values back. The response includes awaited: true, persisted, and a warnings[] array for fields that came back empty. Note: sys_scope is read-only after insert — it is stripped from the payload and reported as a warning (use create_application/create_artifact to set scope at insert time).

Review mode: when sn-scriptsync.agentApi.reviewWrites is on (default off), this write is not sent. It is parked in the VS Code "Pending Saves" queue and the response is { "staged": true, "reviewId": "...", "message": "..." }. The user approves it with Sync Now (or discards it); await is ignored while staged.

Errors:

`update_records`

Update up to 200 existing records on one table in one call. Each row is { "sys_id": "...", ...fields }. Same contract as create_records: one review for the batch, one write-history entry per record, an outcome per row, and no rollback of rows that succeeded. Use update_record_batch instead for several fields on one record.

Requires: browser helper tab connected, SN Utils 10.2.8.0 or later.

Gating: updateRecords, same as update_record (follows createArtifacts where nothing sets it).

Request:

{
  "id": "urecs_1",
  "command": "update_records",
  "instance": "dev12345",
  "params": {
    "table": "incident",
    "continueOnError": true,
    "rows": [
      { "sys_id": "0123456789abcdef0123456789abcdef", "urgency": "2" },
      { "sys_id": "1123456789abcdef0123456789abcdef", "urgency": "2", "assignment_group": "..." }
    ]
  }
}

Parameters: table, rows, continueOnError, dryRun and deadlineMinutes as on create_records. Each row needs a sys_id, at least one field, and may appear only once per call. There is no scope: each record is written in its own application scope (a cross-scope refusal is retried once in the record's scope, as on update_record).

sys_scope in a row is refused with E_INVALID_PARAMS (read-only after insert). This is stricter than update_record_batch, which drops the field and warns.

Response and errors: identical in shape to create_records (mode: "update"), including per-row field warnings when a written field came back empty, different or unverifiable. Collect late or lost results with get_batch_result.

`create_record`

Insert a plain data row on any table: an incident, task, sys_user, sys_user_group, cmdb_ci, catalog request — anything whose display field is not name.

Use create_artifact instead for scriptable artifacts (Script Include, Business Rule, widget): it also tracks the new record in the local workspace and its _map.json.

Gating: createArtifacts (sn-scriptsync.createArtifacts.enabled in VS Code, SNU_ALLOW_CREATE_ARTIFACTS in the standalone snu host) — the same permission as the other create_* commands, on by default.

Request:

{
  "id": "crec_1",
  "command": "create_record",
  "params": {
    "table": "incident",
    "fields": { "short_description": "Printer on 3rd floor is down", "urgency": "2" }
  }
}

Parameters:

Response:

{
  "status": "success",
  "result": {
    "created": true,
    "table": "incident",
    "sys_id": "b1c2...",
    "name": "INC0010001",
    "record": { "...": "..." }
  }
}

record is the inserted row as ServiceNow returned it, so the write is already verified — no follow-up get_record is needed unless you want fields the insert did not return. name is the best available display handle (number, then name, sys_name, short_description).

Errors:

Do not create records by driving the form UI (navigate + set_field + run_ui_action). Those commands exist to exercise real form behaviour (client scripts, UI policies) and to show the user something on screen. As a way to write data they are slow, silently lossy, and leave half-filled forms behind when a step fails.

`create_records`

Insert up to 200 records on one table in one call. Use it instead of looping create_record, and instead of rest_request batch calls or a GlideRecord loop in run_background_script: those reach the instance as one opaque write, while this one gets one review for the whole batch, one write-history entry per record, and an outcome for every row.

Rows that succeed are not rolled back. If row 7 fails, rows 0 to 6 stay written. Never resend the whole batch after a partial failure, or you create duplicates: retry only the rows whose outcome is not succeeded, and query the table first for rows marked unknown.

Requires: browser helper tab connected, SN Utils 10.2.8.0 or later (older helpers answer E_UNSUPPORTED_HOST).

Gating: createArtifacts, same as create_record. With an approve grant the user reviews the batch once in the helper tab (every row is on the card) and the call returns E_REVIEW_PENDING; with auto it runs at once.

Request:

{
  "id": "crecs_1",
  "command": "create_records",
  "instance": "dev12345",
  "params": {
    "table": "sys_choice",
    "scope": "x_acme_app",
    "rows": [
      { "name": "incident", "element": "category", "label": "Network", "value": "network" },
      { "name": "incident", "element": "category", "label": "Storage", "value": "storage" }
    ]
  }
}

Parameters:

Response (all rows written):

{
  "status": "success",
  "result": {
    "batchId": "bat_lzx1y2_a1b2c3d4",
    "table": "sys_choice",
    "mode": "create",
    "effectiveScope": "x_acme_app",
    "running": false,
    "counts": { "total": 2, "succeeded": 2, "failed": 0, "notAttempted": 0, "unknown": 0 },
    "rows": [
      { "index": 0, "outcome": "succeeded", "status": 201, "sys_id": "..." },
      { "index": 1, "outcome": "succeeded", "status": 201, "sys_id": "..." }
    ]
  }
}

Field warnings: every written row is checked against the record the instance answered with. A row whose fields did not stick keeps outcome: "succeeded" (it was written; do not create it again) and gets warnings: [{ "field", "issue" }]:

| issue | meaning |

|---|---|

| empty | a value was sent and the instance stored nothing (dropped by a business rule, field ACL or read-only field) |

| different | the instance stored another value, including a clear ("") that did not take |

| unverified | the answer does not show the field: no read access, an unknown field name, or a type the Table API does not echo (journal fields such as work_notes, passwords, encrypted fields) |

Booleans, numbers and list fields are compared by value ("1" and "true", 0 and "0", b,a and a,b match); a reference sent as a sys_id matches its stored sys_id. counts.withWarnings counts the rows with any warning. Read an empty or different field back with get_record and fix it deliberately; the cause is usually the creation path (the UI does something the Table API does not).

Row outcomes:

| outcome | meaning | retry |

|---|---|---|

| succeeded | the instance answered 2xx; sys_id included | do not retry |

| failed | the instance answered an error; status and error included | retry this row after fixing the cause |

| not_attempted | the batch stopped earlier, was rejected, or hit its deadline | safe to retry this row |

| unknown | the request was sent and no answer arrived | not safe to retry blindly: query the table first |

Overall status: all rows succeeded is success. Otherwise the call is an error whose details carry batchId, counts and every row:

Long batches and lost answers: every call gets a batchId before anything runs (also on E_REVIEW_PENDING, in details). Once a batch was sent, a lost answer (your wait expired, the helper tab disconnected, the bridge stopped) is always E_TIMEOUT with details.batchId, details.cause and details.retrySafe: false: some rows may be written. Do not send the batch again. Call get_batch_result with the batchId once the helper tab is connected, then retry only what it reports as failed or not_attempted. The helper keeps every row's outcome for 24 hours, never runs one batchId twice, and refuses to start a batch at all when it cannot record its progress (E_COMMAND_FAILED, nothing written, safe to retry).

Review mode: with sn-scriptsync.agentApi.reviewWrites on, the batch is staged first as one editable rows file in Pending Saves ({ "staged": true, "batchId": ... }). The user can edit or drop rows; Sync Now validates the edited rows again and only then raises the helper review (when the grant is approve) or runs them. The file stays in Pending Saves, with the user's edits, until the batch has run; after a run, rows that failed or were not attempted go back as a new batch.

Errors:

`create_artifact` ⚡ (RECOMMENDED FOR AI AGENTS)

Create a new artifact directly via payload. This is the preferred method for AI agents - no file creation needed, executes immediately (not queued).

⚠️ IMPORTANT: Transaction Scope Required

The extension automatically includes ?sysparm_transaction_scope=<SCOPE_SYS_ID> in the API request to ensure the artifact is created in the correct scope context.

Request:

{ 
  "id": "11", 
  "command": "create_artifact", 
  "params": { 
    "table": "sys_script_include",
    "scope": "global",
    "fields": {
      "name": "MyNewUtils",
      "script": "var MyNewUtils = Class.create();\nMyNewUtils.prototype = {\n    initialize: function() {},\n    type: 'MyNewUtils'\n};",
      "active": "true",
      "access": "public"
    }
  } 
}

Parameters:

Response:

{
  "status": "success",
  "result": {
    "sys_id": "abc123def456789012345678901234",
    "name": "MyNewUtils",
    "table": "sys_script_include",
    "scope": "global"
  }
}

Synchronous confirmation: add "await": true to read the new record back after creation. The response then includes awaited: true, the persisted field values, and a warnings[] array flagging any requested field that came back empty (e.g. silently dropped).

Benefits over file-based creation:

Example: Creating a Business Rule with table reference:

{
  "id": "12",
  "command": "create_artifact",
  "params": {
    "table": "sys_script",
    "scope": "global",
    "fields": {
      "name": "My Business Rule",
      "collection": "incident",      // ✅ Include table reference in payload
      "script": "// Business Rule script",
      "when": "before",               // ✅ Include when in payload
      "action_insert": "true",        // ✅ Include action in payload
      "active": "true"                // ✅ Include active in payload
    }
  }
}

⚠️ NOTE: All configuration fields (collection, when, action_insert, active) are included in the single payload. These are STRING/BOOLEAN values, not code.

Do NOT create files for configuration fields:

Only the script content (actual code) goes in a file:

If an artifact has multiple code fields, create multiple files:

Example: Creating a REST API Operation with parent reference:

{
  "id": "13",
  "command": "create_artifact",
  "params": {
    "table": "sys_ws_operation",
    "scope": "x_myapp",
    "fields": {
      "name": "getUsers",
      "web_service_definition": "abc123def456",
      "http_method": "GET",
      "operation_script": "(function process(request, response) {\n    response.setBody({message: 'Hello'});\n})(request, response);",
      "active": "true"
    }
  }
}

⚠️ Large / multi-field payloads (widgets etc.): A widget's four big code fields (template, css, script, client_script) are escaping-hell to pass inline on a shell command line (curl -d '...'). Don't hand-build the JSON string — write the request body to a file and send it with curl -d @body.json (build the file with JSON.stringify so newlines/quotes are encoded correctly), or use the file transport. This applies to any multiline or large field value.

Review mode: when sn-scriptsync.agentApi.reviewWrites is on (default off), the record is not created. The request is parked in the VS Code "Pending Saves" queue and the response is { "staged": true, "reviewId": "...", "message": "..." }. The user approves it with Sync Now (which then creates the record and updates _map.json) or discards it; await is ignored while staged. Treat a staged: true response as "queued for human approval", not "created" — the sys_id is only assigned on approval.

Errors:

⚠️ fields.name is required for every table. For a data table whose display field isn't name (e.g. a custom table whose display column is title), don't fight this command — seed rows with rest_request instead: POST /api/now/table/<table> with the row in body (requires sn-scriptsync.restRequest.enabled). create_artifact is for metadata/code artifacts; rest_request POST is the blessed path for plain data rows.

`delete_record` ⚠️ (DESTRUCTIVE — guarded)

Delete a record by table + sys_id, or bulk-delete by query. Disabled by default. Enable sn-scriptsync.deleteRecords.enabled in VS Code settings to allow it. Both hosts (VS Code and the standalone snu bridge) implement the single and the bulk form.

Single delete:

{
  "id": "del_1",
  "command": "delete_record",
  "params": { "table": "incident", "sys_id": "abc123def456..." }
}

The display value (name/number/short_description) is read back first and echoed so you can confirm what was removed.

Bulk delete (query-based): requires confirm: true AND a positive integer limit.

{
  "id": "del_2",
  "command": "delete_record",
  "params": { "table": "incident", "query": "active=false^sys_created_on<javascript:gs.daysAgo(365)", "limit": 50, "confirm": true }
}

Preview without deleting: add "dryRun": true to return the matches that would be deleted. A dry run only reads, so it is never held for review; the delete permission must still be granted.

Parameters:

Response (single):

{ "status": "success", "result": { "deleted": true, "table": "incident", "sys_id": "abc...", "display": "INC0010001" } }

Response (bulk): an outcome per record. deleted is true only when every match was removed; when some fail the command answers E_PARTIAL_FAILURE with the same results list in details.

{ "status": "success", "result": { "deleted": true, "table": "incident", "count": 2, "deletedCount": 2,
  "results": [ { "sys_id": "abc...", "display": "INC0010001", "deleted": true }, { "sys_id": "def...", "display": "INC0010002", "deleted": true } ] } }

Errors:

`create_application`

Create a scoped application (sys_app). The scope is set at insert time — it is read-only afterwards, so this is the correct way to establish a new scope. The resolved scope name → sys_id is recorded in scopes.json so later create_artifact / add_column calls can target it.

Request:

{
  "id": "app_1",
  "command": "create_application",
  "params": { "name": "My Cool App", "prefix": "acme", "short_description": "Demo app" }
}

Parameters:

Response:

{ "status": "success", "result": { "created": true, "name": "My Cool App", "scope": "x_acme_my_cool_app", "sys_id": "..." } }

Errors:

`create_table`

Create a custom table by inserting a sys_db_object record. ServiceNow auto-creates the physical table and its base sys_* fields (sys_id, sys_created_on, sys_updated_on, etc.). Pair it with add_column for your own fields, and set the display column via add_column display: true. This mirrors the create_application / add_column ergonomics so you don't have to drive create_artifact against sys_db_object by hand.

Request:

{
  "id": "tbl_1",
  "command": "create_table",
  "params": { "name": "project", "label": "Project", "scope": "x_acme_myapp", "extends": "task" }
}

Parameters:

Response:

{ "status": "success", "result": { "created": true, "name": "x_acme_myapp_project", "label": "Project", "sys_id": "...", "scope": "x_acme_myapp" } }

Typical table-build flow:

  1. create_table → get the prefixed name back.
  2. add_column for each field (set display: true on the one you want as the display value, plus mandatory / choices / etc. inline).
  3. Seed data rows with rest_request POST /api/now/table/<name> (display field need not be name).

Errors:

`add_column`

Add a column to a table by creating a sys_dictionary entry (keyed by table.element). Use this instead of create_artifact for dictionary entries — it avoids the _map.json name collision where every column would share name = <table>.

Request:

{
  "id": "col_1",
  "command": "add_column",
  "params": { "table": "x_acme_myapp_widget", "element": "priority", "type": "integer", "label": "Priority", "display": true, "mandatory": true, "scope": "x_acme_myapp" }
}

Parameters:

Example with attributes + choices:

{
  "id": "col_2",
  "command": "add_column",
  "params": {
    "table": "x_acme_myapp_project",
    "element": "stage",
    "type": "choice",
    "label": "Stage",
    "display": true,
    "mandatory": true,
    "default": "planning",
    "choices": [
      { "label": "Planning", "value": "planning" },
      { "label": "In Progress", "value": "in_progress" },
      "Done"
    ]
  }
}

Response:

{ "status": "success", "result": { "created": true, "table": "x_acme_myapp_widget", "element": "priority", "type": "integer", "label": "Priority", "sys_id": "...", "choices": ["planning", "in_progress", "Done"] } }

choices is present in the response only when you passed a choices array; it lists the values that were created.

Errors:

`delete_application` ⚠️ (DESTRUCTIVE — cascade)

Delete a scoped application: its scoped metadata (records whose sys_scope is the app) and the sys_app record itself, via a guarded background script. Irreversible. Requires confirm: true and both sn-scriptsync.deleteRecords.enabled and sn-scriptsync.backgroundScripts.enabled.

Request:

{
  "id": "delapp_1",
  "command": "delete_application",
  "params": { "scope": "x_acme_myapp", "confirm": true }
}

Parameters:

Response:

{ "status": "success", "result": { "deleted": true, "name": "My App", "scope": "x_acme_myapp", "childRecordsDeleted": 37 } }

Errors:

Best-effort cascade: it sweeps sys_metadata for the app's scope then deletes sys_app. Some artifact types may need a manual follow-up; verify in the instance afterwards.

`sdk_deploy` (Pro/Trial)

Build, pack and install a ServiceNow SDK (NOW SDK / Fluent) app with the user's browser session, with no separate now-sdk auth login. It runs the project's own now-sdk build and now-sdk pack, then the SN Utils helper tab asks the user to confirm in a modal, installs the package and activates the app's flows. The call waits for that confirmation (up to 15 minutes), so tell the user to confirm in the helper tab. Needs the createArtifacts permission.

Request:

{
  "id": "deploy_1",
  "command": "sdk_deploy",
  "instance": "dev12345",
  "params": { "projectPath": "my-fluent-app" }
}

Parameters:

Without instance, the app's linked instance (the one it was last deployed to or pulled from) is used.

Response:

{ "status": "success", "result": {
  "success": true, "installed": true, "partial": false,
  "app": { "name": "My App", "scope": "x_1234_my_app", "version": "1.0.0" },
  "rollbackUrl": "https://dev12345.service-now.com/sys_rollback_context.do?sys_id=...",
  "flowActivation": { "ok": true, "total": 1, "succeeded": 1, "failed": 0 },
  "durationMs": 8200
} }

Errors:

The result also carries instance, baselineRecorded (the state used for the next change check) and, after a forced deploy, overwritten.

now-sdk dependencies and the other SDK commands still use the SDK's own login.

`sdk_pull` (Pro/Trial)

Pull changes made on the instance into a ServiceNow SDK (NOW SDK / Fluent) project, with the user's browser session and the project's own now-sdk (no separate now-sdk auth login). SN Utils downloads the app package, the SDK converts it into Fluent in a temporary copy of the project, and the differing files are copied into the project. Without instance, the app's linked instance (the one it was last deployed to or pulled from) is used.

Request:

{
  "id": "pull_1",
  "command": "sdk_pull",
  "instance": "dev12345",
  "params": { "projectPath": "my-fluent-app" }
}

Parameters:

Response:

{ "status": "success", "result": {
  "app": { "name": "My App", "scope": "x_1234_my_app", "version": "1.0.0" },
  "instance": "dev12345",
  "changes": [{ "path": "src/server/script-includes/util.js", "status": "modified" }],
  "applied": ["src/server/script-includes/util.js"],
  "upToDate": false
} }

Errors:

`get_record`

Fetch a single record by table + sys_id. Cheaper and simpler than query_records when you already know the sys_id (e.g. to confirm a write).

Request:

{
  "id": "get_1",
  "command": "get_record",
  "params": {
    "table": "incident",
    "sys_id": "abc123def456...",
    "fields": "number,short_description,state,priority"
  }
}

Parameters:

Response:

{
  "status": "success",
  "result": {
    "table": "incident",
    "sys_id": "abc123def456...",
    "record": { "number": "INC0010001", "short_description": "...", "state": "2" }
  }
}

Errors:

`get_table_metadata`

Fetch the columns of a table, including the ones it inherits, with type, reference target, mandatory and read-only flags.

Request:

{ "id": "8", "command": "get_table_metadata", "params": { "table": "sys_script_include", "choices": false } }

Parameters:

Response (VS Code host): columns is the instance's form metadata keyed by column name, as before. fields is the same list normalized:

{
  "result": {
    "columns": { "name": { "label": "Name", "type": "string", "mandatory": false, "max_length": 100 } },
    "fields": [
      { "name": "name", "label": "Name", "internalType": "string", "type": "string", "mandatory": false, "readOnly": false, "maxLength": 100 },
      { "name": "sys_scope", "label": "Application", "internalType": "reference", "type": "reference", "reference": "sys_scope", "mandatory": false, "readOnly": false, "maxLength": 32 }
    ]
  }
}

Response (standalone bridge, snu schema): an array of the same normalized columns. Each keeps the API documentation keys name, label, internalType and exampleValue.

`check_name_exists_remote`

Check if an artifact exists in ServiceNow (queries the actual instance, not just local files).

Request:

{ "id": "9", "command": "check_name_exists_remote", "params": { "table": "sys_script_include", "name": "MyUtils" } }

Response:

{
  "result": {
    "exists": true,
    "sysId": "abc123def456",
    "record": { "name": "MyUtils", "sys_scope": "global" }
  }
}

`pull_records` (alias: `pull_artifacts`)

Pull records from ServiceNow and store their code fields into canonical local workspace files (<instance>/<scope>/<table>/<name>.<field>.<ext> or <table>/<name>/<field>.<ext> for folder-record tables) with automatic _map.json registration.

Key Advantage: Agents call this command over HTTP (port 1977) and never compete for the WebSocket client; the existing SN Utils helper tab remains connected and is required to fulfill the request via the authenticated session.

Request:

{
  "id": "pull_1",
  "command": "pull_records",
  "params": {
    "table": "sys_script_include",
    "query": "nameSTARTSWITHincident^active=true",
    "limit": 10,
    "openFiles": false
  }
}

Parameters:

Response:

{
  "status": "success",
  "result": {
    "table": "sys_script_include",
    "matchedRecords": 2,
    "pulledRecords": 2,
    "filesWritten": 2,
    "skippedEmpty": 0,
    "warnings": [],
    "records": [
      {
        "sys_id": "9659b9900a0a0b340079eb7c8a410eb8",
        "name": "IncidentUtils",
        "scope": "global",
        "files": [
          {
            "field": "script",
            "path": "dev12345/global/sys_script_include/IncidentUtils.script.js",
            "bytes": 1420,
            "action": "updated"
          }
        ]
      }
    ]
  }
}

Behavior & Rules:

Errors:

`pull_scope`

Pull every scriptable artifact of one application scope into canonical local workspace files (<instance>/<scope>/<table>/<name>.<field>.<ext>, or <table>/<name>/<field>.<ext> for folder-record tables) with _map.json registration, so an agent can work from local files instead of fetching artifacts one by one. This is the Agent API counterpart of the VS Code Load Scope button.

The command first lists which artifact tables the application actually uses, then walks each table that sn-scriptsync knows how to write to disk, paging past the Table API limits. Tables without code fields (properties, roles, ACL rows without scripts, ...) are reported under skippedTables and not written.

Request:

{
  "id": "pull_scope_1",
  "command": "pull_scope",
  "params": { "scope": "x_acme_app" }
}

Parameters:

Response:

{
  "result": {
    "scope": { "name": "x_acme_app", "sys_id": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6" },
    "folder": "dev221527/x_acme_app",
    "tables": [
      { "table": "sys_script", "matchedRecords": 12, "pulledRecords": 12, "filesWritten": 12, "skippedEmpty": 0, "truncated": false },
      { "table": "sys_script_include", "matchedRecords": 140, "pulledRecords": 140, "filesWritten": 140, "skippedEmpty": 0, "truncated": false }
    ],
    "totals": { "tables": 2, "records": 152, "filesWritten": 152, "skippedEmpty": 0 },
    "skippedTables": [ { "table": "sys_properties", "records": 4, "reason": "no_scriptable_fields" } ],
    "warnings": [],
    "complete": true,
    "outcome": "complete"
  }
}

outcome says what the pull achieved. Check it, not only the HTTP status:

When the instance dictionary cannot be read for a table, known tables fall back to the field definitions bundled with sn-scriptsync and snu, with a warning; a table is only reported as no_scriptable_fields when its dictionary was read completely.

Existing local files for the same records are refreshed in place and keep their file names through _map.json; a remote field that is now empty clears the local file. Run it again at any time to re-sync the whole application.

`analyze_artifact_type`

Read-only. Samples existing artifacts of one type on the instance and compares them into a type profile: what records make up one artifact of this type, how often each appears, what the platform creates for you, what the creation path changes, and what the scan could and could not see. Use it before building a composite artifact you have not built on this instance in this project, then build with create_records and ask the user about everything labeled choice.

When to use it, and when not: it costs many reads and returns a large result.

Supported types in this version: table (root sys_db_object) and catalog_item (root sc_cat_item). UI Builder pages are not profiled by this command.

Requires: browser helper tab connected. No permission gate: every request is a GET through the helper tab, as the connected user. The profile is written to the local workspace (<instance>/_profiles/), never to the instance.

Request:

{ "id": "prof_1", "command": "analyze_artifact_type", "instance": "dev12345", "params": { "type": "table", "scope": "x_acme_app" } }

Parameters:

Reading the profile:

Errors:

`query_records` ⚡

Execute an arbitrary encoded query against any ServiceNow table. Use this to fetch data, check conditions, or explore records.

Request:

{ 
  "id": "q1", 
  "command": "query_records", 
  "params": { 
    "table": "incident",
    "query": "priority=1^active=true",
    "fields": "number,short_description,priority,state,sys_created_on",
    "limit": 5,
    "orderBy": "ORDERBYDESCsys_created_on"
  } 
}

Parameters:

Keep results small: always pass fields and limit. The defaults are four fields and 10 rows, and the result says when they applied.

Field paths are checked before the query runs. ServiceNow silently ignores a condition on a field that does not exist and returns unfiltered rows, so every path in query, fields (when you pass it) and orderBy is checked hop by hop against the table schema, including dot-walks and the field inside ORDERBY, DYNAMIC, OR/NQ branches. Values are not judged: javascript:gs.beginningOfToday() is fine once its field exists. Keyword search (123TEXTQUERY321) is supported. A related-list block (RLQUERY<table>.<field>,…^…^ENDRLQUERY) is checked against its own table; one without ENDRLQUERY is refused. A ref_<table> cast passes only when <table> really extends the reference target (checked in sys_db_object).

Response:

{
  "status": "success",
  "result": {
    "table": "incident",
    "count": 3,
    "records": [
      {
        "sys_id": "abc123",
        "number": "INC0010001",
        "short_description": "Server down",
        "priority": "1",
        "state": "2",
        "sys_created_on": "2024-12-07 10:30:00"
      },
      ...
    ]
  }
}

What the result left out: besides table, count and records, the result carries limit, more (true when more records match than were returned), total (the instance's own count, when it reports one), defaultFields / defaultLimit (true when the defaults applied) and a note in words. With more: true, raise limit or narrow the query; never treat the first page as everything.

Common Query Examples:

| Use Case | Query |

|----------|-------|

| Get single record by sys_id | sys_id=abc123def456... |

| Active P1 incidents | priority=1^active=true |

| Recent changes | ORDERBYDESCsys_created_on |

| My assigned tasks | assigned_to=javascript:gs.getUserID()^active=true |

| Open problems | state!=7^state!=8 |

| Items in scope | sys_scope.scope=x_myapp |

| Name contains | nameLIKEutils |

| Created today | sys_created_onONToday@javascript:gs.beginningOfToday()@javascript:gs.endOfToday() |

Encoded Query Operators:

`get_parent_options`

Get available parent records for reference fields. Use this to find existing REST API services, tables, etc.

Request:

{ 
  "id": "10", 
  "command": "get_parent_options", 
  "params": { 
    "table": "sys_ws_definition",
    "scope": "x_myapp",
    "nameField": "name",
    "limit": 50
  } 
}

Parameters:

Response:

{
  "result": {
    "table": "sys_ws_definition",
    "count": 3,
    "options": [
      { "sys_id": "abc123", "name": "My REST API", "scope": "x_myapp" },
      { "sys_id": "def456", "name": "Another API", "scope": "global" },
      { "sys_id": "ghi789", "name": "Third API", "scope": "x_myapp" }
    ]
  }
}

Common use cases:

| Creating | Query table | To get |

|----------|-------------|--------|

| REST API Operation | sys_ws_definition | Available REST API services |

| Business Rule | sys_db_object | Available tables |

| UI Action | sys_db_object | Available tables |

| Client Script | sys_db_object | Available tables |

`code_search` ⚡ (Pro feature)

Run the SN Utils GraphQL field-index code search across ServiceNow script tables and return structured matches. This is the same engine as the SN Utils code search page — far better than a plain query_records LIKE at finding where a term actually lives in scripts (script includes, business rules, UI actions, client scripts, fix scripts, etc.). Use it to discover existing code before writing new artifacts.

Requires: an active SN Utils Pro / Trial / Enterprise license in the connected browser helper tab. Without it the command returns E_DISABLED.

Request:

{
  "id": "cs_1",
  "command": "code_search",
  "instance": "dev12345",
  "params": {
    "term": "sn_appclient dev mode",
    "activeOnly": false,
    "limit": 50
  }
}

Parameters:

Response:

{
  "status": "success",
  "result": {
    "term": "sn_appclient dev mode",
    "stats": { "tables": 3, "records": 7, "matches": 12, "searchedTables": ["sys_script_include", "sys_script", "sys_ui_action"] },
    "words": ["sn_appclient", "dev", "mode"],
    "results": [
      {
        "tableName": "sys_script_include",
        "tableLabel": "Script Include",
        "rowCount": 2,
        "hits": [
          {
            "sysId": "abc123...",
            "name": "AppClientUtils",
            "sysClassName": "sys_script_include",
            "active": true,
            "matches": [
              {
                "field": "script",
                "fieldLabel": "Script",
                "matchingWords": ["dev", "mode"],
                "context": "...if (current.dev_mode) { ... }...",
                "lineMatches": [
                  { "lineNumber": 42, "content": "  var devMode = gs.getProperty('sn_appclient.dev_mode');", "isMatch": true }
                ]
              }
            ],
            "missingWords": null,
            "parentRef": null
          }
        ]
      }
    ]
  }
}

Response shape:

Notes:

Errors:

`rest_request` (guarded generic passthrough)

Make an arbitrary ServiceNow REST call through the connected browser session (reuses its authentication). The escape hatch for anything the typed commands don't cover.

Gating:

Both hosts implement this command. Over MCP it is also reachable as the snu_rest_request tool, and a plain record insert has a dedicated wrapper, snu_create_record, that returns the inserted record instead of a raw HTTP envelope.

Request:

{
  "id": "rest_1",
  "command": "rest_request",
  "params": {
    "endpoint": "/api/now/table/incident",
    "method": "GET",
    "queryParams": { "sysparm_limit": "1", "sysparm_query": "active=true" }
  }
}

Parameters:

Response:

{ "status": "success", "result": { "status": 200, "data": { "result": [ { "...": "..." } ] } } }

Errors:

`run_background_script` ⚠️ (guarded — runs server-side code)

Execute a server-side background script (/sys.scripts.do) on the instance and return its captured output. Runs as the connected browser user, in the global scope. Disabled by default — enable sn-scriptsync.backgroundScripts.enabled.

Request:

{
  "id": "bg_1",
  "command": "run_background_script",
  "params": { "script": "gs.print('Active incidents: ' + new GlideAggregate('incident').getRowCount());" }
}

Parameters:

Response:

{ "status": "success", "result": {
  "executed": true,
  "output": "[0:00:00.1] Script completed … <PRE>*** Script: Active incidents: 42<BR/>[CacheFlushLog] …</PRE>",
  "stdout": "Active incidents: 42",
  "warnings": [], "errors": [], "logLines": ["[CacheFlushLog] …"],
  "executionId": "47eea1d697485f14c3e2fc90f053af06",
  "status": "completed"
} }

Errors:

The pragmatic escape hatch for bulk data fixes that the typed commands don't cover. Output is whatever /sys.scripts.do returns (the gs.print lines plus the server's evaluation log).

`list_tables`

List available table folders in the instance.

Request:

{ "id": "3", "command": "list_tables" }

Response:

{
  "result": {
    "tables": ["sys_script_include", "sys_script", "sp_widget"]
  }
}

`list_artifacts`

List artifacts in a specific table.

Request:

{ "id": "4", "command": "list_artifacts", "params": { "table": "sys_script_include" } }

Response:

{
  "result": {
    "artifacts": ["global/MyUtils.script.js", "global/HelperFunctions.script.js"]
  }
}

`check_name_exists`

Check if an artifact name already exists (checks local _map.json files only, not ServiceNow).

Request:

{ "id": "5", "command": "check_name_exists", "params": { "table": "sys_script_include", "name": "MyUtils" } }

Response:

{
  "result": {
    "exists": true,
    "sysId": "abc123def456"
  }
}

`get_file_structure`

Get the expected file naming convention.

Request:

{ "id": "6", "command": "get_file_structure" }

Response:

{
  "result": {
    "pattern": "{instance}/{scope}/{table}/{name}.{field}.{ext}",
    "example": "myinstance/global/sys_script_include/MyUtils.script.js",
    "fields": {
      "sys_script_include": ["script"],
      "sys_script": ["script"],
      "sp_widget": ["script", "css", "client_script", "link", "template"]
    }
  }
}

`validate_path`

Validate a proposed file path before creating it.

Request:

{ "id": "7", "command": "validate_path", "params": { "path": "myinstance/global/sys_script_include/NewUtil.script.js" } }

Response:

{
  "result": {
    "valid": true,
    "parsed": {
      "instance": "myinstance",
      "scope": "global",
      "table": "sys_script_include",
      "file": "NewUtil.script.js"
    }
  }
}

`open_in_browser`

Open an artifact in the browser. For widgets, opens the preview page; for other artifacts, opens the form view.

Request (with sys_id):

{ 
  "id": "3", 
  "command": "open_in_browser", 
  "params": { 
    "table": "sp_widget",
    "sys_id": "abc123def456"
  } 
}

Request (with name - looks up sys_id from _map.json):

{ 
  "id": "3", 
  "command": "open_in_browser", 
  "params": { 
    "table": "sp_widget",
    "name": "MyWidget",
    "scope": "global"
  } 
}

Response:

{
  "result": {
    "opened": true,
    "url": "https://instance.service-now.com/$sp.do?id=sp-preview&sys_id=abc123def456",
    "table": "sp_widget",
    "sys_id": "abc123def456"
  }
}

URL patterns by table:

| Table | URL Pattern |

|-------|-------------|

| sp_widget | /$sp.do?id=sp-preview&sys_id={sys_id} (Widget Preview) |

| sp_page | /sp?id={name} (Portal Page) |

| Other tables | /{table}.do?sys_id={sys_id} (Standard Form) |

`get_served_url`

Resolve the URL an artifact is actually served at — without opening a tab. UI pages render at <instance>/<name>.do, Service Portal pages at /sp?id=..., widgets in the preview harness — not at their record form. Handy before navigate_and_screenshot or for sharing a link.

Handles the scoped prefix automatically. A UI page named todo_app in scope x_acme_app is stored with the unprefixed name todo_app, but ServiceNow serves it at /x_acme_app_todo_app.do. This command reads the record's scope (sys_scope.scope) and prepends it (guarding against double-prefixing if the name already carries the scope), so you get /x_acme_app_todo_app.do — not the 404-prone /todo_app.do.

Request:

{ "id": "url_1", "command": "get_served_url", "params": { "table": "sys_ui_page", "name": "my_page" } }

Parameters:

Response:

{ "status": "success", "result": { "url": "https://dev.service-now.com/x_acme_app_my_page.do", "table": "sys_ui_page", "name": "my_page" } }

Errors:

`refresh_preview`

Refresh browser tabs showing the artifact preview. Useful after updating a widget to see changes immediately.

Request:

{ 
  "id": "4", 
  "command": "refresh_preview", 
  "params": { 
    "table": "sp_widget",
    "sys_id": "abc123def456"
  } 
}

Request (with name):

{ 
  "id": "4", 
  "command": "refresh_preview", 
  "params": { 
    "table": "sp_widget",
    "name": "MyWidget",
    "scope": "global"
  } 
}

Response:

{
  "result": {
    "refreshed": true,
    "sys_id": "abc123def456",
    "testUrls": [
      "https://instance.service-now.com/$sp.do?id=sp-preview&sys_id=abc123def456*",
      "https://instance.service-now.com/sp?id=mywidget*"
    ],
    "message": "Refresh command sent for sp_widget"
  }
}

Note: This refreshes ALL browser tabs matching the widget's preview URLs, plus the active tab if it's on the same instance.

`take_screenshot` ⚡ (Remote - Async)

Take a screenshot of a ServiceNow page. The browser picks the best capture path it actually has — no capability juggling needed on your side:

  1. activeTab (tab already granted): captures directly, as always.
  2. Chrome debugger: when the grant is missing and the connected build supports it (Debug edition + Pro + sn-scriptsync.browserDebugger.enabled), the browser captures via the debugger instead — no user action, just a brief flash of Chrome's debugger banner. The result carries "capturedVia": "debugger".
  3. Ask the user: only when neither path works does E_SCREENSHOT_PERMISSION surface — the user must click the SN Utils extension icon on the target tab, and a retry is built in (see below).

Permission notes (regular build — most users):

Request:

{
  "id": "14",
  "command": "take_screenshot",
  "params": {
    "url": "https://instance.service-now.com/sp?id=my_widget"
  }
}

Parameters:

Response (success):

{
  "id": "14",
  "command": "take_screenshot",
  "status": "success",
  "timestamp": 1733779200000,
  "result": {
    "saved": true,
    "filePath": "/workspace/screenshots/screenshot_2024-12-09T14-00-00.png",
    "fileName": "screenshot_2024-12-09T14-00-00.png",
    "url": "https://instance.service-now.com/sp?id=my_widget",
    "tabTitle": "My Widget - ServiceNow",
    "capturedVia": "activeTab"
  }
}

capturedVia is "activeTab" or "debugger" — which path actually produced the image.

Response (permission needed):

{
  "id": "14",
  "command": "take_screenshot",
  "status": "error",
  "code": "E_SCREENSHOT_PERMISSION",
  "error": "Screenshot requires permission. Click the SN Utils extension icon on the tab you want to capture, then retry."
}

The extension auto-retries once (~10s) after a permission error before surfacing E_SCREENSHOT_PERMISSION, giving the user time to click the extension icon — so a "slow" screenshot call usually means the grant flow is in progress, not a hang. The retry stays pinned to the tab selected by the first attempt so a ServiceNow redirect cannot open duplicate tabs.

Use cases:

Behavior:

  1. Screenshots are saved to {workspace}/screenshots/ folder
  2. The browser extension must be connected
  3. Tab reuse: Requests prefer an open tab on the same ServiceNow instance; retries stay pinned to the selected tab, and later screenshots reuse the last captured tab when possible
  4. If no matching tab is found, a new tab will be opened

Handling permission errors:

If E_SCREENSHOT_PERMISSION surfaces, the debugger route was already tried or isn't available — inform the user they need to click the SN Utils extension icon, then retry the screenshot command. (If the error's details say cdpFallbackAvailable: true, the build could do debugger captures but the user hasn't enabled sn-scriptsync.browserDebugger.enabled — you can mention that as an alternative.)

`navigate_and_screenshot`

Open/activate a URL, wait for it to finish loading, settle briefly, then screenshot that exact tab — collapsing the activate → sleep → screenshot dance into one call. The PNG is saved under screenshots/.

Request:

{
  "id": "nss_1",
  "command": "navigate_and_screenshot",
  "params": { "url": "https://dev.service-now.com/incident.do?sys_id=-1", "settleMs": 1500 }
}

Parameters:

Response:

{ "status": "success", "result": { "saved": true, "filePath": ".../screenshots/screenshot_....png", "tabId": 42, "url": "https://dev.service-now.com/incident.do?sys_id=-1", "tabTitle": "Incident | ServiceNow", "navigated": true } }

Verify url/tabTitle match the page you intended — cheaper than rendering the image.

Errors:

`run_slash_command` ⚡ (Remote - Async)

Execute SN Utils slash commands on a ServiceNow tab. Particularly useful for debugging forms with /tn (show technical names).

⚠️ IMPORTANT: Only use DOCUMENTED slash commands!

Documented commands include:

❌ Do NOT use non-existent commands like /click, /select, etc.

Request:

{
  "id": "14",
  "command": "run_slash_command",
  "params": {
    "command": "/tn",
    "url": "https://*.service-now.com/*",
    "autoRun": true
  }
}

Parameters:

Response (success):

{
  "id": "14",
  "command": "run_slash_command",
  "status": "success",
  "timestamp": 1733779200000,
  "result": {
    "executed": true,
    "status": "completed",
    "summary": { "status": "completed", "state": "enabled", "enabled": true, "total": 8, "visible": 8 },
    "slashCommand": "/tn",
    "tabId": 12345,
    "autoRun": true
  }
}

Response (error):

{
  "id": "14",
  "command": "run_slash_command",
  "status": "error",
  "error": "No ServiceNow tab found matching: https://*.service-now.com/*"
}

Completion status:

result.status is dispatched, completed, cancelled, or error. executed is retained for compatibility and only confirms delivery. Always inspect the status before deciding what to do next.

Additional built-in results (updated SN Utils and ScriptSync required):

| Command | result.summary |

| --- | --- |

| /tn | state: enabled, disabled, mixed, or unavailable; enabled: true, false, or null for mixed/unavailable; total and visible: technical-name element counts across reachable frames. Waits for Workspace toggling to finish. These are element counts, not field counts or viewport visibility. |

| /bg, /xml | url and tabId of the tab the helper created. result.tabId remains the source tab. The new tab stays in the background unless focus: true. /xml resolves the current active form and requires a saved record. |

| /token | refreshed: true and origin identifying the refreshed instance. No token or credentials are included in the summary. Existing session-refresh permission checks still apply. |

Random-fill completion (/rnd):

With an updated SN Utils extension, autoRun: true waits for the built-in /rnd to finish, including dependent fields and retries. The ScriptSync Agent API returns result.summary:

Workspace filling requires SN Utils Pro, Enterprise or an active Pro trial. UI16 and Service Portal remain available on Free. Without the required entitlement, a Workspace request returns the standard Agent API error E_PRO_REQUIRED with details.status: "error", before writing any fields. The stripped Community build does not include Workspace filling. This gate is identical for manual use and agent requests; do not retry a blocked fill through another command or script.

{
  "status": "completed",
  "ui": "workspace",
  "table": "incident",
  "sysId": "0123456789abcdef0123456789abcdef",
  "mode": "mandatory",
  "total": 4,
  "filled": 3,
  "skipped": 1,
  "pending": 0,
  "revalidated": 3
}

Why /tn matters:

When debugging form issues, you need to know the actual field names (not just labels). The /tn command toggles the display of technical field names on any ServiceNow form.

Before /tn:

Short Description: [Server is down]
Priority: [1 - Critical]
Assignment Group: [Network Support]

After /tn:

short_description: [Server is down]
priority: [1 - Critical]
assignment_group: [Network Support]

Recommended debugging workflow:

1. User reports form issue: "The priority field won't save"

2. AI activates the form tab and runs /tn:
   { "command": "run_slash_command", "params": { 
     "command": "/tn",
     "url": "https://*.service-now.com/*incident*"
   }}
   
3. AI takes a screenshot to see the technical field names:
   { "command": "take_screenshot", "params": { 
     "url": "https://*.service-now.com/*incident*" 
   }}
   
4. Now AI knows the exact field name (e.g., "priority") 
   to investigate in Business Rules, Client Scripts, etc.

`activate_tab` ⚡ (Remote - Async)

Find and activate a browser tab by URL pattern. Useful for navigating to specific ServiceNow pages or ensuring a tab is ready before taking screenshots.

Request:

{
  "id": "14",
  "command": "activate_tab",
  "params": {
    "url": "https://*.service-now.com/nav_to.do*",
    "reload": true,
    "waitForLoad": true,
    "openIfNotFound": false
  }
}

Parameters:

Response (success):

{
  "id": "14",
  "command": "activate_tab",
  "status": "success",
  "timestamp": 1733779200000,
  "result": {
    "activated": true,
    "tabId": 12345,
    "url": "https://instance.service-now.com/nav_to.do?uri=incident.do?sys_id=abc123",
    "title": "Incident | ServiceNow",
    "opened": false,
    "reloaded": true
  }
}

Response (tab not found):

{
  "id": "14",
  "command": "activate_tab",
  "status": "error",
  "error": "No tab found matching: https://*.service-now.com/nav_to.do*"
}

Use cases:

URL Pattern Examples:

| Pattern | Matches |

|---------|---------|

| https://*.service-now.com/* | Any ServiceNow page |

| https://myinstance.service-now.com/sp?id=my_widget* | Specific widget page |

| https://*.service-now.com/nav_to.do* | Any classic UI page |

| https://*.service-now.com/$sp.do?id=sp-preview* | Widget preview pages |

Workflow: Activate tab → Take screenshot:

1. Activate tab with reload to ensure fresh content
   { "command": "activate_tab", "params": { 
     "url": "https://*.service-now.com/sp?id=my_widget*", 
     "reload": true, 
     "waitForLoad": true 
   }}
   
2. Take screenshot (tab is already active and ready)
   { "command": "take_screenshot", "params": { 
     "url": "https://instance.service-now.com/sp?id=my_widget" 
   }}

`switch_context` ⚡ (Remote - Async)

Switch ServiceNow context: update set, application scope, or domain. This uses the ServiceNow UI Concourse Picker API to change the active context in the browser session.

Request:

{
  "id": "15",
  "command": "switch_context",
  "params": {
    "switchType": "updateset",
    "value": "abc123def456789012345678901234",
    "reloadTab": true,
    "tabUrl": "https://*.service-now.com/*"
  }
}

Parameters:

Response (success):

{
  "id": "15",
  "command": "switch_context",
  "status": "success",
  "timestamp": 1733779200000,
  "result": {
    "success": true,
    "switchType": "updateset",
    "value": "abc123def456789012345678901234",
    "reloaded": true
  }
}

Response (error):

{
  "id": "15",
  "command": "switch_context",
  "status": "error",
  "error": "Invalid switchType. Must be one of: updateset, application, domain"
}

Use cases:

Finding the sys_id:

Before switching context, you may need to query for the sys_id:

1. Find update set sys_id:
   { "command": "query_records", "params": { 
     "table": "sys_update_set", 
     "query": "name=My Update Set^state=in progress", 
     "fields": "sys_id,name,state" 
   }}
   
2. Find application sys_id:
   { "command": "query_records", "params": { 
     "table": "sys_scope", 
     "query": "scope=x_myapp", 
     "fields": "sys_id,scope,name" 
   }}
   
3. Find domain sys_id:
   { "command": "query_records", "params": { 
     "table": "domain", 
     "query": "name=My Domain", 
     "fields": "sys_id,name" 
   }}

Examples:

Switch to a specific update set:

{ 
  "id": "sw1", 
  "command": "switch_context", 
  "params": { 
    "switchType": "updateset", 
    "value": "abc123def456..." 
  } 
}

Switch application scope (e.g., before creating artifacts):

{ 
  "id": "sw2", 
  "command": "switch_context", 
  "params": { 
    "switchType": "application", 
    "value": "xyz789ghi012..." 
  } 
}

Switch domain:

{ 
  "id": "sw3", 
  "command": "switch_context", 
  "params": { 
    "switchType": "domain", 
    "value": "dom456jkl789..." 
  } 
}

Workflow: Find update set → Switch → Create artifact:

1. Query for update set
   { "command": "query_records", "params": { 
     "table": "sys_update_set", 
     "query": "nameLIKEMyFeature^state=in progress", 
     "fields": "sys_id,name" 
   }}
   
2. Switch to the update set (using sys_id from response)
   { "command": "switch_context", "params": { 
     "switchType": "updateset", 
     "value": "<sys_id from step 1>" 
   }}
   
3. Create artifact (now goes into correct update set)
   { "command": "create_artifact", "params": { 
     "table": "sys_script_include", 
     "scope": "global", 
     "fields": { "name": "MyNewUtils", "script": "..." } 
   }}

`upload_attachment` ⚡ (Remote - Async)

Upload a file (image, document, etc.) as an attachment to any ServiceNow record.

Gating: createArtifacts (sn-scriptsync.createArtifacts.enabled in VS Code, SNU_ALLOW_CREATE_ARTIFACTS in the standalone snu host, or the per-instance grant in the SN Utils helper tab) — on by default. An upload inserts a sys_attachment row, so it carries the same permission as the other create_* commands and returns E_DISABLED when that permission is off.

Request (using filePath - recommended):

{
  "id": "15",
  "command": "upload_attachment",
  "params": {
    "table": "incident",
    "sys_id": "abc123def456789012345678901234",
    "filePath": "screenshots/screenshot_2024-12-09.png"
  }
}

Request (using imageData - base64):

{
  "id": "15",
  "command": "upload_attachment",
  "params": {
    "table": "incident",
    "sys_id": "abc123def456789012345678901234",
    "fileName": "screenshot_2024-12-09.png",
    "imageData": "iVBORw0KGgoAAAANSUhEUgAA...",
    "contentType": "image/png"
  }
}

Parameters:

Response (success):

{
  "id": "15",
  "command": "upload_attachment",
  "status": "success",
  "timestamp": 1733779200000,
  "result": {
    "uploaded": true,
    "fileName": "screenshot_2024-12-09.png",
    "table": "incident",
    "recordSysId": "abc123def456789012345678901234",
    "attachment": {
      "sys_id": "xyz789...",
      "size_bytes": "45678",
      "content_type": "image/png"
    }
  }
}

Response (error):

{
  "id": "15",
  "command": "upload_attachment",
  "status": "error",
  "error": "HTTP 403: Access denied"
}

Use cases:

Combining with take_screenshot:

A powerful workflow is to take a screenshot and then upload it as an attachment:

1. Take screenshot of a widget/page
   { "command": "take_screenshot", "params": { "url": "..." } }
   Response includes: "filePath": "/workspace/screenshots/screenshot_2024-12-09_143022.png"
   
2. Upload as attachment using the ABSOLUTE filePath from the response
   { "command": "upload_attachment", "params": { 
     "table": "incident", 
     "sys_id": "...", 
     "filePath": "/workspace/screenshots/screenshot_2024-12-09_143022.png"
   }}

⚠️ IMPORTANT: File Path Resolution

The upload_attachment command resolves relative paths from the instance folder, not the workspace root.

Always use ABSOLUTE paths for files outside the instance folder:

// ❌ WRONG - relative path will look in instance folder
{ "filePath": "screenshots/screenshot.png" }
// Resolves to: /workspace/empakooi/screenshots/screenshot.png (NOT FOUND)

// ✅ CORRECT - use absolute path from take_screenshot response
{ "filePath": "/Users/me/workspace/screenshots/screenshot.png" }
// Finds the actual file

Best practice: Copy the filePath value directly from the take_screenshot response.

Note: Using filePath eliminates the need to manually read and base64-encode files. The extension handles this automatically.

Supported content types (auto-detected from file extension):

| Extension | contentType |

|-----------|-------------|

| .png | image/png |

| .jpg, .jpeg | image/jpeg |

| .gif | image/gif |

| .webp | image/webp |

| .svg | image/svg+xml |

| .pdf | application/pdf |

| .txt | text/plain |

| .json | application/json |

| .xml | application/xml |

| .html | text/html |

| .css | text/css |

| .js | application/javascript |

| .zip | application/zip |

| .doc | application/msword |

| .docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |

| .xls | application/vnd.ms-excel |

| .xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |

| Other | application/octet-stream |


`download_attachment` (bytes to a file, never to you)

Download one attachment (sys_attachment sys_id) to a file in the workspace. The result carries the file path, size, content type and sha256, never the bytes, so a binary file never lands in your context. Process the file locally (resize, convert, inspect) and send it back with upload_attachment using relativePath or filePath from the result.

Needs a current SN Utils helper tab (capabilities.attachmentDownload in get_capabilities); an older one answers E_UNSUPPORTED_HELPER. A read: no permission gate.

Request:

{ "id": "dl_1", "command": "download_attachment", "params": { "sys_id": "68cf699a97485f14c3e2fc90f053af5d" } }

Parameters:

Response:

{ "status": "success", "result": {
  "downloaded": true, "sys_id": "68cf699a97485f14c3e2fc90f053af5d",
  "filePath": "/workspace/dev1/attachments/68cf699a97485f14c3e2fc90f053af5d/lineup.png",
  "relativePath": "attachments/68cf699a97485f14c3e2fc90f053af5d/lineup.png",
  "fileName": "lineup.png", "sizeBytes": 1748088, "contentType": "image/png",
  "sha256": "…", "sourceTable": "sc_cat_item", "sourceSysId": "73da21de97085f14c3e2fc90f053aff3"
} }

The file is written to a temporary file first and published atomically only after its size and sha256 match what the helper read, so a file at filePath is always complete.

Errors:


`delete_attachment` ⚠️ (DESTRUCTIVE — guarded)

Delete one attachment through the Attachment API, which removes the sys_attachment row and its stored content. Prefer it over delete_record on sys_attachment.

Gating: the deleteRecords permission, like delete_record, including the helper-tab Review Queue when the instance gate is Approve (E_REVIEW_PENDING, then get_review_result). In snu, pass confirm: true (or --confirm).

Request:

{ "id": "dat_1", "command": "delete_attachment", "params": { "sys_id": "68cf699a97485f14c3e2fc90f053af5d" } }

Parameters:

Response:

{ "status": "success", "result": { "deleted": true, "sys_id": "68cf…", "fileName": "lineup.png", "table": "sc_cat_item", "tableSysId": "73da…", "sizeBytes": 1748088 } }

Errors: E_NOT_FOUND (nothing deleted), E_DISABLED, E_REVIEW_PENDING, E_USER_REJECTED.


Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.