# AISDL AIScript Language Specification AIScript expresses the business implementation of a Process. It uses named functions, local values, objects, arrays, calculations and declared Services. It does not expose a host programming language or deployment configuration. AISDL means AI System Design Language and covers the complete System specification. AIScript is its Process coding language. This document defines its syntax, values, interfaces and execution behavior. ## Coding Contract AIScript's grammar and documented interfaces are the coding contract. Use the exact method names, argument order, accepted types and return types defined here. Do not infer additional methods from another language or a similar API. You own the business logic and may combine the documented capabilities freely. If a required operation cannot be expressed through them, identify the precise missing capability rather than inventing an interface. Before delivering code, check every call and language construct against this contract. Correct known syntax, type and interface errors in the code itself. Deliver complete code matching its Process contract, not pseudocode or placeholders. The same source-accuracy requirement applies when describing, summarizing or enumerating AIScript interfaces, not only when writing code. Examples must agree with the grammar and interface definitions. If you find a conflict, identify it rather than silently choosing or inventing behavior. ## 1. Process And Code A System still has its manifest, Collections, Audiences, Services, Secrets, Events and Processes. Their resource specifications remain separate from the programming language. `../../Process.md` defines the Process contract. It owns Inputs, Outputs, Audience, invocation, authentication and App presentation. Code implements that contract. It contains no endpoint specification, access policy, listener installation or deployment configuration. AIScript code is a separate `.ais` resource, normally `processes//code.ais`. It contains one `execute(input)` function and any number of helpers. The resource path is relative to the System root, not to this documentation folder. ```text execute(input) return { greeting: greet(input.name) } end greet(name) return "Hello " + name end ``` `execute` receives the declared Inputs. Its returned value must match the declared Outputs. A helper returns a value to its caller, not to the external client. Helpers may appear before or after their callers. There are no executable statements or variables outside functions. No business domain, resource count, workflow shape or implementation strategy is prescribed by this language. ## 2. Source And Blocks - Source is UTF-8. Names are case-sensitive. - Function and variable names use letters, digits and underscores, beginning with a letter. Resource names are string values and follow the System resource naming rules. - A function starts with its name and parameters and ends with `end`. There is no `function`, `fn` or `to` keyword. - Statements end at a newline. Within parentheses, brackets or braces, a newline continues the expression. Indentation is for readability and has no execution meaning. Semicolons are not used. - A block introduced by `if`, `for each`, `while`, `switch`, `try`, `async` or `timer` ends with `end`. - Strings use double quotes and JSON escapes. Numeric literals are base ten; a decimal point or exponent makes a decimal literal. A leading minus is unary negation. - Object keys can be unquoted names or quoted strings. Quoted keys support paths such as `"supplier.id"`. Duplicate literal keys are an authoring error. - Comments are `//` to the end of a line or `/* ... */` across lines. Block comments do not nest. Comment markers inside strings are text. Definitions are recognized at file level. A similar `name(arguments)` form inside a function is a call. Function names, parameters, utility namespaces and execution-context names cannot be ambiguously reused in the same scope. ## 3. Variables And Functions `name = value` creates or updates a local variable. Parameters are local variables. No declaration keyword is needed. Assignment to an existing variable must preserve its compatible type; integer-to-decimal promotion is allowed. A nullable value may alternate between its value type and null. Variables belong to a function call, not to a shared Process object. An assignment in an ordinary conditional or loop updates that function's local variable. A variable must be assigned on every possible path before it is read. Loop item names exist only within their loop; they cannot hide an existing local name. Helpers do not capture their caller's variables: pass arguments explicitly. Primitive values are passed by value. Objects and arrays are shared by reference within one execution. `Object.copy(value)` creates an independent deep copy of data. Service and resource handles passed to helpers continue to refer to their original execution-owned resources. Async has a separate copy boundary described below. Helpers have fixed positional parameters and no hidden optional parameters. A helper may return a value or return without a value, but not mix both styles. A no-value call is a statement and cannot be assigned or used in an expression. Falling through a no-value helper is equivalent to `return`. Every successful path through `execute` must return its result, including an explicitly empty result when its contract has no Outputs. Types come from Inputs, Outputs, Collection fields, method signatures and expressions. Runtime checks handle data whose shape is unknown until execution. Unknown data is not permission to invoke undocumented methods. Recursion is allowed; operational limits govern execution time, call depth and memory, not the number of business resources in a design. ## 4. Values | Type | Meaning | | --- | --- | | `string` | Unicode text. | | `integer` | A signed 64-bit whole number. | | `decimal` | A base-ten calculation value. | | `boolean` | `true` or `false`, never a truthy string or number. | | `date` | A calendar date with no time or timezone. | | `datetime` | A point in time, represented with an offset or UTC. | | `object` | Named data properties. | | `array` | An ordered sequence of typed data values. | | `bytes` | An immutable byte sequence. | | `duration` | An elapsed amount of time, not a date. | | `null` | Explicit absence of a value. | Collection references and File values retain their resource-defined shapes. Resource type text maps to the string code type; resource type long maps to the checked integer code type. An identifier is a string or integer according to its Collection; it is not an additional primitive type. A File Input is metadata, not bytes and not a storage handle. There is no competing number code type. Services, records, cursors, protocol messages, mail, channels, files and streams are typed handles. Only their specified fields and methods are accessible. Reflection, prototypes, host-class construction/imports and dynamic code evaluation are not part of AIScript. `object.name` and `object[key]` access one property. Missing object properties read as null. `Object.has(object, key)` distinguishes a missing property from an explicit null. Reading through null fails with `InvalidInput`; it does not create intermediate objects. Arrays use zero-based checked integer indices. An invalid index fails rather than producing an undefined value. Assignments to object properties and existing array positions update those values. `array.add(value)` adds one item at the end and has no result. It is a statement-only method call: do not assign, return or chain its result. The value must match the array's declared item type when one is specified. Explicit null properties must survive copies and permitted serialization. ## 5. Expressions And Calculations Operands and call arguments evaluate once, from left to right. `and` and `or` short-circuit. Precedence, from strongest to weakest, is: 1. Member/index access and calls. 2. Unary minus and `not`. 3. `*`, `/`, `%`. 4. `+`, `-`. 5. `==`, `!=`, `<`, `<=`, `>`, `>=`. 6. `and`. 7. `or`. Parentheses override precedence. Conditions must be boolean. Numeric comparison compares values, including integer/decimal promotion; strings compare Unicode code-point sequences. Dates and datetimes compare only with the same type. Null supports equality and inequality, not ordering. Structured equality is explicit through `Object.equal`, not handle identity or an inherited host-language rule. Integer addition, subtraction, multiplication, negation and remainder are exact within the signed 64-bit range. Overflow fails with `InvalidInput`. `%` accepts integers and has the dividend's sign. Decimal addition, subtraction and multiplication use exact decimal intermediates. Mixing integer and decimal promotes the integer. Division produces a decimal; zero divisors fail. `/` requires a terminating decimal result. For rounded division, use `divide(value, divisor, places, rounding)`. ```text subtotal = sum line.total for each line in lines tax = round(subtotal * rate, places, "half-up") average = divide(subtotal, count, places, "half-even") ``` The aggregation binds its item name explicitly. Its source is an array, it evaluates each projected numeric value once, and an empty source returns the zero of the inferred numeric type. A non-numeric item fails. It does not infer a query or fetch more records. `round(value, places, rounding)` and `divide(value, divisor, places, rounding)` return decimals. `places` is a non-negative integer. Rounding names are `half-up`, `half-even`, `up`, `down`, `ceiling`, `floor` and `unnecessary`. Up/down mean away from/toward zero; ceiling/floor mean toward positive/negative infinity. `unnecessary` fails if rounding would change the value. Precision is not silently selected from a currency or from the machine locale. `+` also concatenates two strings. There is no implicit string/number conversion, loose equality, NaN or infinity. ### Numeric Values Integer and decimal literals retain their source digits. Calculations do not silently convert an exact integer or decimal into an approximate value. Numeric serialization preserves the value's digits. Non-finite values fail. A declared numeric Output is not silently converted to a string; use explicit conversion when the Output contract requires text. ## 6. Control Flow ```text if amount < 0 fail InvalidInput "Amount cannot be negative" else if amount == 0 return { status: "empty" } else return { status: "ready" } end ``` `for each item in values` visits an array in order or consumes a cursor in its documented forward order. `while condition` tests before each iteration. `break` exits the nearest loop; `continue` advances it. Changing an array's length while iterating that same array is an error; construct another array or iterate a copy. `switch value` contains `case expression` clauses and an optional `else` clause. Cases are evaluated in order; the first equal scalar value runs. There is no fall-through. One `end` closes the switch. No match without `else` does nothing. `return value` exits the current function. `return` without a value is allowed only in a no-value helper. `execute` must return the shape specified by its Process. ## 7. Eight Failures | Name | Meaning | HTTP mapping | | --- | --- | --- | | `InvalidInput` | Supplied data is invalid. | 400 | | `Unauthenticated` | Authentication is missing or invalid. | 401 | | `Forbidden` | The operation is not permitted. | 403 | | `NotFound` | The requested resource does not exist. | 404 | | `Conflict` | The current state prevents the operation. | 409 | | `LimitExceeded` | An applicable limit has been reached. | 429 | | `Unavailable` | A required capability is temporarily unavailable. | 503 | | `InternalError` | An unexpected execution failure occurred. | 500 | Business code uses the names, not transport numbers: ```text fail NotFound "Customer not found" ``` `fail Name message` evaluates the string message and raises that named failure. These are the only failure categories. An ordinary business outcome such as a declined application belongs in declared Outputs. Authentication and access management remain runtime responsibilities; listing failure names does not move those responsibilities into business code. Uncaught failures propagate automatically. Use `catch` only when handling a failure, not just to throw it again. `fail InvalidInput "Invalid amount"` raises a failure; `throw failure` propagates an existing caught failure when handling cannot resolve it. `throw` does not take a failure name and message. Cleanup belongs in `finally`; cleanup alone does not require a catch. `try` may have ordered `catch Name` clauses, a final `catch failure` for any remaining failure, and/or `finally`. A named clause handles exactly that category. A general catch binds an immutable object with `name` and a safe `message`; internal causes remain diagnostic information. `throw failure` preserves the caught failure. No explicit return, fail, throw or control-flow escape is permitted in `finally`. If cleanup itself fails while another failure is propagating, preserve the original failure and attach the cleanup failure to internal diagnostics. A cleanup failure without a prior failure propagates normally. Unsupported arguments and failed conversions map to InvalidInput. A unique-constraint or state conflict maps to Conflict. Explicit permission denials map to Forbidden. Network timeouts and temporary provider failures map to Unavailable. Unexpected execution failures map to InternalError. An HTTP response with an unsuccessful status is still a response; the author interprets its business meaning. Failure categories do not depend on matching human-readable messages. Catching a failure does not undo side effects. A database failure that leaves its transaction unusable makes that execution scope rollback-only. Catching it cannot turn the scope into a successful commit. There is no automatic retry, rollback compensation or remote failover. ## 8. Services Every Service is declared in the System using `../../Service.md` and its schema. Acquire it inside a function by its exact name: ```text database = service "database_sales" partner = service "tcp_partner" with { RequestProtocol: "request-message", ResponseProtocol: "response-message" } ``` The optional `with` object supplies lookup parameters, not a replacement Service specification. The current execution scope supplies lifecycle and request context. Database, email, HTTP, TCP, storage, both caches, messaging and secrets follow the same declaration, lookup and ownership rules. Names do not select an implementation. Authors may pass handles to helpers in the same execution. The following catalog defines each Service's callable interface. Use its documented parameter types, result types and defaults. Another Service needs a declared callable interface before code can use it. Do not invent methods or substitute placeholder behavior. `value` below means supported data. `none` means a statement-only operation: it cannot be assigned. Optional arguments show their defaults explicitly. Null is an ordinary value only where the signature allows it. Runtime-owned Services and cursors must not be manually closed by author code. ### Byte Arguments When a Service method expects bytes, AIScript converts the supplied value using these rules: | Supplied value | Bytes passed to the Service | | --- | --- | | Object, array, integer, decimal, boolean, date, datetime or duration | Serialize with `Object.asString`, then encode as UTF-8. | | String | Encode as UTF-8 without JSON quoting. | | Bytes | Pass unchanged. | All AIScript data values are supported by `Bytes.encode`. Null passed explicitly to `Bytes.encode` becomes the UTF-8 bytes of `null`. At a Service boundary, null keeps the method's documented meaning: an optional HTTP body of null means no body, while a required bytes argument rejects null. Use `Bytes.encode(null)` when the intended payload is JSON null. Serialization follows the JSON interface's rules, including numeric precision and rejection of handles or cycles. File metadata can be serialized as data; it does not read the file's contents. Obtain Record data or file contents through their documented methods before encoding; a live handle is not a data value. The same rules apply to `Bytes.encode(value)` when a bytes value is needed explicitly. For signing an outgoing payload, convert it once, then pass that same bytes value to both `sign` and the sending method. Do not sign one serialization and send another. For incoming signature verification, use the original received bytes, not a parsed and reserialized object. Conversion does not choose HTTP headers or a partner's canonicalization rules. ### Database | Call | Result | | --- | --- | | `db.create(collection)` | Unsaved Record for the named Collection. | | `db.first(query)` | Record or null. | | `db.query(query)` | Forward Cursor of Records. | | `db.count(query)` | Integer count. | | `db.update(query)` | Bulk update of matching records; returns integer affected row count. | | `record.load(values)` | none; assign the supplied fields to pending record state. | | `record.remove(name)` | none; clear the named field's value in pending record state. Persist with save. | | `record.save()` | none; persist pending state in the execution transaction. | | `record.data()` | Plain object containing the loaded projection, recursively converted to data. | `record.field` reads a loaded field. Assignment changes its pending value. Unknown or unselected fields fail; property access does not fetch extra fields. A reference assignment is an object containing the target identity: `order.supplier = { id: supplierId }`. Arrays of IDs are not automatically arrays of linked records. Return its identity or `data()` according to the Output contract, not an opaque Record handle. For a single-record change, load the Record with `db.first`, check its business state, assign its changed fields and call `save`. Use a base-row lock when required for concurrency. For example, changing a loaded reference uses `order.supplier = { id: supplierId }` followed by `order.save()`; soft deletion uses `record.deleted = true` followed by `record.save()`. When processing query results individually, change and save each Record rather than issuing `db.update` for each identity. See [update-record.ais](examples/update-record.ais). Use `db.update` for bulk changes applying the same update to matching records. A bulk filter may happen to match zero, one or many records; that does not change its purpose. See [bulk-update.ais](examples/bulk-update.ais). To clear an optional field, call `record.remove("notes")` and then `record.save()`. This clears the stored value, not the field definition or the record. Field constraints still apply. Removal is statement-only, not a chained call. See [remove-record-value.ais](examples/remove-record-value.ais). Soft deletion remains a separate operation: set `deleted` to true and save. Queries use objects, not SQL strings: ```text query = { from: "PurchaseOrder (id, supplier (id, name), total)", where: { "supplier.id": input.supplierId, deleted: false }, orderBy: { timestamp: "desc" }, offset: input.offset, count: input.count } ``` `from` names a Collection and optional loaded field/reference projection. `where` binds ordinary condition values as parameters. A scalar condition is equality. A condition object has `op` and, where needed, `value`. Scalar comparisons support eq, neq, gt, gte, lt and lte; nil/nnil test null; in/nin take non-empty arrays; btw/nbtw take two-element arrays; like and ilike use database patterns. Negate a condition with `negate: true`. `and`/`or` contain arrays of condition objects. Repeated constraints on a field use these groups. Query pattern semantics belong to the database Service, not the Text utility. The complete query interface, projections, functions and named condition snippets are in [Database Queries](Database-Queries.md). ```text where = { and: [ { deleted: false }, { timestamp: { op: "gte", value: start } }, { timestamp: { op: "lt", value: end } } ] } ``` `orderBy` maps fields to asc/desc. Offset is non-negative; count is positive. Use stable ordering with an ID tie-breaker when paging requires it. `locking: { type: "forUpdate" }` belongs to reads; lock only the base row before separately loading optional references. Update uses `from`, `where` and non-empty `set`; `set: { "supplier.id": supplierId }` changes a local reference, not the Supplier row. Zero affected rows is not automatically NotFound. Normal reads explicitly include `deleted: false`. Soft deletion is setting deleted and saving. No physical record-delete operation is exposed. Filters and uniqueness rules are explicitly defined by the author, not inferred from business names. ### HTTP | Call or field | Result | | --- | --- | | `http.send(body = null, overrides = null)` | HttpResult, or null for configured asynchronous submission. | | `result.status` | Integer HTTP status. | | `result.headers` | Case-insensitive object of arrays of header values. | | `result.bytes` | Response bytes. | The body is the first argument: `http.send({ reference: input.reference })` sends UTF-8 JSON using the declared request settings. The optional second argument overrides verb, path, headers, timeout or async for that call, for example `http.send(payload, { timeout: 5000 })`. Use `http.send()` for no body and no overrides, or `http.send(null, { verb: "get", path: "https://partner.example/status" })` for a bodyless request with overrides. A one-argument object is always the body, never inferred to be overrides. Configured URLs, TLS, content-type headers and Secrets remain in the Service declaration or supported overrides. Only post/put/patch send a body through this interface. Response bytes are decoded and parsed explicitly. Asynchronous HTTP submission discards its response and is not durable delivery. AIScript `async` and an HTTP Service's async option are different operations. ### TCP | Call | Result | | --- | --- | | `tcp.getRequestProtocol()` | Protocol selected by lookup parameters. | | `protocol.newMessage()` | Message following that protocol. | | `message.load(values)` | none; assign protocol section data. | | `message.data()` | Plain object of decoded sections and fields. | | `tcp.send(message, asynchronous = false)` | Response Message, or null for asynchronous submission. | Messages follow the section structure of the declared protocol. Framing, field encoding, bitmaps and TLV belong to the protocol resource defined in `../../Service.md`, not hand-built network plumbing in Process code. Async TCP submission performs and discards the complete exchange according to the Service contract. No arbitrary socket or binary-protocol implementation is implied. ### Email | Call | Result | | --- | --- | | `smtp.create(subject, content, contentType = "text/plain", data = null, features = null)` | Mail. | | `mail.send(recipients)` | none; queue the message. | Recipients are an array of `{ scope: "to" | "cc" | "bcc", email: string }`. At least one valid recipient is required. Data and features are objects when present. Omitted trailing arguments use the defaults in the signature. Queueing is not confirmation of delivery or a durable business notification workflow. Escape inserted values in HTML. ### Storage And Files | Call or field | Result | | --- | --- | | `storage.root()` | Root Folder. | | `folder.get(path)` | File/Folder handle or null. | | `folder.newFolder(path)` | Folder, creating it according to the Service contract. | | `folder.newFile(path)` | New File; exclusive creation fails with Conflict if an entry already exists. | | `folder.list(pattern, visitor)` | none; invoke the named one-argument helper for each entry. | | `entry.name`, `entry.path`, `entry.size`, `entry.modifiedAt` | String, String, integer bytes, datetime. | | `entry.isFile()`, `entry.isFolder()` | Boolean. | | `file.asString()`, `file.asBytes()` | Text or bytes under the Service's read contract. | | `file.write(textOrReadStream)` | none; write text or stream data. | | `file.openRead()` | Owned ReadStream. | | `file.openWrite(append = false)` | Owned WriteStream. | | `stream.read(count)` | Up to count bytes, or null at EOF; count must be positive. | | `stream.write(bytes)` | none; WriteStream only. | | `stream.close()` | none; release an owned stream, safely repeatable. | Large files can be processed in chunks. Always close author-opened streams in finally; scope cleanup is the safety net. No stream may outlive its owning scope. Listing order is unspecified; a visitor takes one entry and returns no value. Storage paths are relative to the configured root. Absolute paths, parent traversal and links escaping that root fail. Use System-owned folders for generated content. The platform-managed upload staging and finalized cdn folders are not author-managed output folders. A File Input's ID identifies finalized media according to that File contract; it is not an arbitrary relative path. Metadata, storage objects and bytes remain distinct. Returning a storage File for download does not create a new public URL. ### Local And Shared Cache | Call | Result | | --- | --- | | `cache.get(key)` | Data value or null. | | `cache.put(key, value, ttlSeconds)` | none. | | `cache.remove(key)` | none. | | `cache.containsKey(key)` | Boolean. | The local Service also accepts `put(key, value)` under its configured expiry rules. Local values are independent per JVM/Service and disappear on restart/unload. Shared values are visible to clients of the same configured cache. Structured data is copied into/out of both caches, so mutating a returned object does not mutate the stored entry. Handles cannot be stored in a cache. For local cache, zero adds no per-entry limit, a negative TTL fails, and configured expiry/capacity still applies. For shared cache, zero or negative requests an ordinary non-expiring write according to that Service contract. This existing distinction is explicit, not silently normalized. Keys must be namespaced by the System's declared convention when the cache is shared. Cache operations do not join database transactions. ### Messaging | Call | Result | | --- | --- | | `bus.newChannel()` | Channel owned by the current scope. | | `channel.publish(subject, bytes, properties = null)` | none; await broker acknowledgment. | Acknowledgment does not mean that consuming Processes completed. Event payloads match their declared shape and encoding. Consumption and payload-to-Input mapping belong to Event/Process resources; code does not install a listener. Deliveries may repeat. Database writes and message publication do not become atomic because they occur in one function. ### Secrets Acquire a declared Secrets Service like any other Service, using its exact declared name. Call the methods below on that Service value. There is no global `SecretsProvider` object in AIScript. The underlying provider is the runtime's default. ```aiscript execute(input) secrets = service "secrets_default" token = secrets.tokenize(input.text, input.ttlSeconds) restored = secrets.detokenize(token) return { text: Bytes.decode(restored) } end ``` This code requires a declared `secrets_default` Service and a Process contract with string Input `text`, integer Input `ttlSeconds` and string Output `text`. The Service name is author-chosen and must match the Process dependency. `tokenize` and `detokenize` below are Service methods, not global functions. Every property locating a declared Secret or provider key starts with `security.secrets.`. Stored object Secrets are retrieved as a string and parsed as JSON. Options passed to sign/verify are ordinary method arguments, not an invented Secret property. | Call | Result | | --- | --- | | `getSecret(path, key)` | Stored string, or null if absent according to the provider contract. | | `putSecret(path, key, value, ttlSeconds)` | none. | | `removeSecret(path, key)` | none; missing is already removed. | | `encrypt(keyId, bytes)` | Opaque ciphertext string. | | `decrypt(keyId, ciphertext)` | Bytes. | | `sign(keyId, bytes, options = null)` | Base64 signature string. | | `verify(keyId, bytes, signature, options = null)` | Boolean; check it. | | `hash(keyId, bytes)` | Keyed HMAC-SHA256 bytes. | | `newKeyPair(ttlSeconds)` | Object with key and secret strings, not an asymmetric key pair. | | `tokenize(bytes, ttlSeconds)` | Opaque provider token. | | `detokenize(token)` | Bytes, not an external partner access token. | | `newSSLContext(keyId, certId, trustIds...)` | Opaque TLS context usable only by interfaces explicitly accepting it. | sign/verify options support algorithm HmacSHA256, SHA256withRSA, RSASSA-PSS or SHA256withECDSA, subject to the configured provider. Missing/empty options select HmacSHA256. keyVersion, when supported, is a positive integer. Unsupported operations fail; the language does not implement cryptography itself. Signature verification over a received body uses its original bytes, not reserialized JSON. Provider expiry caps requested TTL; a shorter supported lifetime wins. Zero does not override provider limits. Provisioning, approval, rotation, provider administration and expiry policy belong to the security process, not business code. Secret removal is not key destruction or a claim of erasing backups/history. Filesystem-backed secret handling is development-only. ## 9. Utility Interfaces Utilities perform local computation. They never hide communication with undeclared Services. Optional arguments below have defaults; other omissions, wrong types and invalid values fail with InvalidInput. None of these functions mutate an argument unless explicitly stated. ### Text And Conversion | Call | Meaning | | --- | --- | | `Text.size(text)` | Integer Unicode code-point count. | | `Text.trim(text)` | Remove leading/trailing Unicode whitespace. | | `Text.lower(text)`, `Text.upper(text)` | Locale-independent case conversion. | | `Text.contains(text, part)` | Boolean literal substring test. | | `Text.startsWith(text, part)`, `Text.endsWith(text, part)` | Boolean. | | `Text.split(text, separator)` | Array of literal-separated parts, including empty parts. Empty separator fails. | | `Text.join(strings, separator)` | Concatenated string; elements must be strings. | | `Text.replace(text, search, replacement)` | Replace all literal occurrences; empty search fails. | | `Text.slice(text, start, count)` | Checked code-point range. | | `Text.escapeHtml(text)` | Escape text for insertion into HTML text content, not a URL or script context. | | `Text.format(template, values)` | String with `{{path.to.value}}` replacements. Missing paths fail; no expressions or code execute. | | `Text.matches(text, pattern)` | Full-string match using the portable pattern subset below. | | `Numbers.integer(value)` | Checked integral conversion from a finite numeric value or base-ten string. | | `Numbers.decimal(value)` | Decimal conversion from integer/decimal or finite base-ten string. | | `Numbers.text(value)` | Locale-independent numeric text without grouping. | | `Numbers.min(values)`, `Numbers.max(values)` | Numeric minimum/maximum; empty fails. | | `Numbers.abs(value)` | Numeric absolute value; integer overflow fails. | | `Numbers.format(value, places, rounding)` | Fixed-place numeric string, using explicit rounding. | The portable pattern subset supports literals, character classes/ranges, Unicode category escapes, dot, anchors, grouping, alternation and bounded/unbounded quantifiers. It excludes backreferences, lookaround and implementation-specific flags. Matching is case-sensitive. Invalid patterns fail. Engine-specific extensions are not implicit language capabilities. Integer strings have optional sign and decimal digits only. Decimal strings also accept decimal points/exponents. Conversions consume the entire string; whitespace, grouping separators and numeric prefixes are rejected. Boolean conversion is explicit through `Values.boolean(value)`, accepting boolean or exactly "true"/"false". `Values.text(value)` accepts scalar values, not opaque handles or arbitrary object stringification. ### Objects And Arrays Objects are maps of named properties, written as `{ name: value }`; arrays are ordered values written as `[value]`. `Object` supplies helpers for these values and their text representation. Ordinary fields still use `value.field` or `value[key]`. | Call | Meaning | | --- | --- | | `Object.has(object, key)` | Direct property presence. | | `Object.get(object, path, fallback = null)` | Nested dot-path lookup with fallback for missing paths, not explicit null. | | `Object.keys(object)` | Own keys in insertion order. | | `Object.remove(object, key)` | none; remove one direct local property. | | `Object.copy(value)` | Deep copy data; reject cyclic data and handles. | | `Object.equal(left, right)` | Structural equality of data; object key order ignored, array order significant. | | `array.add(value)` | none; add one item to the end of this array. Mutates the array; statement-only. | | `Arrays.size(array)` | Integer length. | | `Arrays.contains(array, value)` | Structural data membership. | | `Arrays.slice(array, start, count)` | New array of the checked range. | | `Arrays.map(array, helper)` | New array of helper(item) results, in order. | | `Arrays.filter(array, helper)` | New array of items for which helper(item) returns true. | | `Arrays.sort(array, helper)` | New stable ordered array; helper(left, right) returns negative/zero/positive integer. | | `Object.parse(text)` | Data read from its text representation; invalid text and duplicate property names fail. | | `Object.asString(value, indent = 0)` | Text representation of data; preserves nulls and numeric digits, rejects handles and cycles. Durations become ISO-8601 elapsed-duration strings; nested bytes become Base64 strings. | | `Values.boolean(value)`, `Values.text(value)` | Explicit scalar conversion as defined above. | Helpers supplied as arguments are named functions in the same code resource. No anonymous functions or captured closures are required. Generic object keys that contain dots use direct indexing rather than a dot-path utility. Object.copy deep-copies data. Arrays.map and Arrays.filter produce new containers but retain referenced data items unless the helper copies them. Object.parse preserves integer digits and base-ten decimal text without an intermediate floating-point parse. Date/datetime JSON values serialize as ISO strings and parse as strings unless decoded by a declared typed contract or Dates utility. ### Dates And Durations | Call | Meaning | | --- | --- | | `Dates.now()` | Current datetime. | | `Dates.today(timezone)` | Current calendar date in the named timezone. | | `Dates.date(isoText)` | Parse yyyy-MM-dd strictly. | | `Dates.datetime(isoText)` | Parse an ISO datetime containing an explicit offset or Z. | | `Dates.parse(text, kind, pattern, timezone = null, policy = null)` | Parse date/datetime using an explicit pattern and policies. | | `Dates.add(value, amount, unit, options = null)` | Add an integer amount with the rules below. | | `Dates.startOfDay(date, timezone)` | Earliest valid instant on that local date; a wholly skipped date fails. | | `Dates.before(left, right)`, `Dates.after(left, right)` | Same-type comparison. | | `Dates.between(start, end, unit)` | Decimal elapsed datetime difference in milliseconds/seconds/minutes/hours. | | `Dates.format(value, pattern, timezone = null)` | String; datetime formatting requires explicit timezone, date formatting does not. | | `Durations.of(amount, unit)` | Duration from integer milliseconds/seconds/minutes/hours. | | `Durations.between(start, end)` | Signed elapsed duration between datetimes. | | `Durations.amount(duration, unit)` | Decimal conversion to an elapsed unit. | Date arithmetic accepts days/weeks/months/years. Datetime arithmetic in milliseconds/seconds/minutes/hours is elapsed; days/weeks/months/years requires options.timezone and preserves local clock time. Unsupported type/unit combinations fail. No JVM-default timezone is used. Invalid timezone names and impossible dates fail. Month/year arithmetic defaults to the last valid destination day; `options.monthEnd: "reject"` requests failure instead. A local datetime that lies in a daylight-saving gap or overlap is rejected unless policy explicitly supplies `gap: "forward"` and/or `overlap: "earlier" | "later"`. These choices never depend on the server's timezone. Pattern fields are yyyy, MM, dd, HH, mm, ss, SSS and XXX, with quoted literal text; kind is date or datetime. Invalid input is not leniently rolled into another month. A date-only parse does not accept time fields. For reporting, use a start-inclusive/end-exclusive pair of local day boundaries. Adding one calendar day is not adding 24 elapsed hours. ### Bytes | Call | Meaning | | --- | --- | | `Bytes.encode(value, charset = "UTF-8")` | Any AIScript data value as bytes: strings encode directly, bytes pass unchanged, all other data values serialize as JSON and encode. The charset applies to the resulting text; unencodable text fails. Handles and cycles fail. | | `Bytes.decode(bytes, charset = "UTF-8")` | String; reject malformed sequences. | | `Bytes.size(bytes)` | Integer byte count. | | `Bytes.slice(bytes, start, count)` | New checked byte range. | | `Bytes.concat(parts)` | New bytes from an array of byte sequences. | | `Bytes.base64(bytes)`, `Bytes.fromBase64(text)` | Standard padded Base64 encode/strict decode. | | `Bytes.hex(bytes)`, `Bytes.fromHex(text)` | Lowercase hexadecimal encode; strict even-length decode. | The standard charsets are UTF-8, US-ASCII and ISO-8859-1. Byte-valued Service arguments use UTF-8 for automatic text conversion. Use `Bytes.encode(value, charset)` explicitly for a partner requiring a different encoding. An existing bytes value remains unchanged regardless of charset. Binary responses are not silently decoded or parsed. Other encodings require an explicitly documented interface. Bytes are immutable; operations construct new sequences rather than mutate shared data. ## 10. Execution Context And Results `property(path, fallback = null)` reads local System properties. There are no mandatory business property names. Secret locations and key identifiers always use the security.secrets prefix. `call "ProcessName" with inputs` invokes a declared same-System Process and returns its typed Outputs. Its name is a resource reference, not a URL or generated ID. It must be callable on the internal channel. Publication resolves routing; code does not assemble paths. Cross-System communication uses a declared Service. Direct child calls and ordinary helpers do not independently commit shared database work. Ordinary results use `return object`. Additional forms are `return text string`, `return bytes bytesValue`, `return file storageFile` and `return redirect url`. A File metadata Output uses ordinary structured return, not `return file`. A redirect is restricted to HTTP(S), does not imply authentication and does not itself complete a later callback. Each return can have `with metadata`, an object with optional status, contentType, filename and headers. Status is one of ok/created/accepted/noContent/seeOther/temporaryRedirect or an explicit valid HTTP status for a documented integration requirement. These are response metadata, not extra failure names or endpoint specifications. JSON/text/bytes/file default to status ok; redirect defaults to seeOther. JSON defaults to application/json and text to text/plain with UTF-8. Bytes require contentType, and file uses explicit metadata or its declared content type. noContent requires null as the returned body. filename is a suggested download name, not a filesystem path. Headers cannot override hop-by-hop headers or contradict the selected body encoding. Filename/header values containing CR, LF or NUL fail; download names cannot contain path separators. Typed result validation still applies to the Process's selected transport response contract. Advanced incoming transport access is available through an immutable invocation view: | Call | Result | | --- | --- | | `request.bytes()` | Original received body bytes, or null. | | `request.text(charset = "UTF-8")` | Strictly decoded body text, or null. | | `request.header(name)` | First case-insensitive header value, or null. | | `request.headers(name)` | Array of all values, empty when absent. | | `request.parameter(name)` | One decoded mapped transport parameter, or null. | | `request.origin()` | Configured external origin, not an untrusted Host header. | | `processUrl(name)` | External URL assigned to a declared HTTP Process in the running System. | Body access must retain original bytes for verification. A typed internal invocation may have structured Inputs without an original byte sequence; bytes() then returns null. Callback/body/parameter mapping is explicit in the Process integration contract; accessors do not invent it. There is no identity administration or request-principal binding logic in this language contract. ## 11. Transactions, Async And Timers The runtime owns the request database transaction. Reusing the same database Service in that context, including through direct child calls, shares its transaction. Saving a record does not commit. Success commits and error completion rolls back, subject to rollback-only state. Separate database Services are not an automatic distributed transaction. HTTP, mail, cache, storage and messaging effects do not roll back with it. ```text async sendReceipt(receipt) end ``` Async copies the captured data values at submission, returns immediately and never retains the caller's request, response, transaction or Service instances. Captured dates, integers and decimals preserve their types and precision. A handle cannot cross this boundary, including through a helper or nested object. The async block can modify its own copied values but cannot mutate the parent's variables. Each async block has an independently owned execution scope. A Service is obtained by the same `service "name"` syntax inside that scope, including within a helper. Its database transaction is separate from the caller's. The same runtime access rules apply; async does not grant new permissions. No handle crosses scopes. Services acquired inside async belong to that async execution and are released when it ends. They are never borrowed from the caller. Work may start before the parent commits. Async is not after-commit, durable, exactly-once or automatically retried. Its failure is collected under the originating activity correlation, but cannot change a response already sent. Shutdown stops accepting new work and requests cooperative cancellation of running work; it does not promise to finish or replay it. Durable business stages require stored work and separately invoked Processes. `timer interval unit timeout amount unit repeat count` is valid only within async. Timeout and repeat are independently optional, but at least one is required. Units are milliseconds/seconds/minutes/hours; amounts and repeat are positive integers. It waits before the first iteration, runs sequentially and starts no iteration after its timeout or repeat budget is exhausted. The bounds do not preempt an in-progress blocking call; that call needs its Service timeout. `stop` exits the nearest Timer successfully. Exhaustion without stop raises Unavailable in the async scope. The Timer preserves its own plain-data state between iterations. Each iteration owns a fresh Service/transaction scope and releases it before waiting again; handles cannot enter from outside an iteration or survive into another. Data assignments may persist; handles may not. This avoids holding a database transaction open while waiting. A Timer is still in-memory and not a replacement for scheduled Process invocation. ## 12. Comments And Descriptive Annotations Comments explain business decisions and meaningful operations, not every punctuation mark. Keep them beside the operations they describe. ```text /* * @Security: applicable security standard * @Requirement: verified requirement identifier, when known * @Control: protection actually implemented below * @Evidence: operation providing evidence */ ``` `@Standard` and `@Conformance` describe business/protocol standards and implemented behavior. These lines remain comments, not endpoint specifications, permissions, security configuration or proof of certification. Do not add irrelevant annotations or invented requirement numbers. ## 13. Consistency The code must agree with its Process Inputs, Outputs, dependencies and documented behavior. References use exact resource names. Every field, method, Event payload and Process call must match its declared interface. Do not replace an intended integration with fictional results. The author owns business completeness and consistency across resources. The specifications do not prescribe a business scope, a resource count or a payment-specific design. The examples illustrate syntax, interfaces and behavior. Their resource prerequisites are listed explicitly. Use the actual business contracts when creating a System rather than treating the example names and fields as required business resources. ## 14. Grammar This grammar defines source structure. Semantic rules above constrain otherwise valid syntax. NEWLINE means a logical newline outside strings and bracketed expressions. Blank lines and comments are ignored. A statement before end/else/case/catch/finally still ends with a logical newline. Source indentation does not create a block. Trailing commas in source argument, array and object lists are accepted; JSON text parsed by Object.parse remains strict JSON. ```ebnf program = { function } ; function = name, "(", [ parameters ], ")", NEWLINE, block, "end", NEWLINE ; parameters = name, { ",", name }, [ "," ] ; block = { statement } ; statement = assignment | expressionStatement | return | failure | throw | if | for | while | switch | try | async | timer | "break", NEWLINE | "continue", NEWLINE | "stop", NEWLINE ; assignment = target, "=", expression, NEWLINE ; target = name, { ".", name | "[", expression, "]" } ; expressionStatement = expression, NEWLINE ; return = "return", [ [ format ], expression, [ "with", object ] ], NEWLINE ; format = "text" | "bytes" | "file" | "redirect" ; failure = "fail", failureName, expression, NEWLINE ; throw = "throw", name, NEWLINE ; if = "if", expression, NEWLINE, block, { "else", "if", expression, NEWLINE, block }, [ "else", NEWLINE, block ], "end", NEWLINE ; for = "for", "each", name, "in", expression, NEWLINE, block, "end", NEWLINE ; while = "while", expression, NEWLINE, block, "end", NEWLINE ; switch = "switch", expression, NEWLINE, { "case", expression, NEWLINE, block }, [ "else", NEWLINE, block ], "end", NEWLINE ; try = "try", NEWLINE, block, { catch }, [ "finally", NEWLINE, block ], "end", NEWLINE ; catch = "catch", ( failureName | name ), NEWLINE, block ; async = "async", NEWLINE, block, "end", NEWLINE ; timer = "timer", integerLiteral, elapsedUnit, [ "timeout", integerLiteral, elapsedUnit ], [ "repeat", integerLiteral ], NEWLINE, block, "end", NEWLINE ; expression = orExpression ; orExpression = andExpression, { "or", andExpression } ; andExpression = comparison, { "and", comparison } ; comparison = addition, [ comparisonOp, addition ] ; comparisonOp = "==" | "!=" | "<" | "<=" | ">" | ">=" ; addition = multiplication, { ( "+" | "-" ), multiplication } ; multiplication = unary, { ( "*" | "/" | "%" ), unary } ; unary = [ "not" | "-" ], postfix ; postfix = primary, { ".", name | "[", expression, "]" | "(", [ arguments ], ")" } ; primary = name | stringLiteral | integerLiteral | decimalLiteral | "true" | "false" | "null" | object | array | "(", expression, ")" | service | processCall | sum ; arguments = expression, { ",", expression }, [ "," ] ; object = "{", [ entry, { ",", entry }, [ "," ] ], "}" ; entry = ( name | stringLiteral ), ":", expression ; array = "[", [ arguments ], "]" ; service = "service", stringLiteral, [ "with", object ] ; processCall = "call", stringLiteral, "with", expression ; sum = "sum", expression, "for", "each", name, "in", expression ; failureName = "InvalidInput" | "Unauthenticated" | "Forbidden" | "NotFound" | "Conflict" | "LimitExceeded" | "Unavailable" | "InternalError" ; elapsedUnit = "millisecond" | "milliseconds" | "second" | "seconds" | "minute" | "minutes" | "hour" | "hours" ; ``` An expression statement must be a call with effects; an unused literal is an error. A switch requires at least one case. A try requires a catch or finally. Finally, fail/throw, mutation and resource operations have the scope/type restrictions defined above. Names matching control-flow keywords, failure names, builtin functions or utility namespaces cannot be redeclared. The return-format words text/bytes/file/redirect are contextual keywords only immediately after return. Keywords may appear as unquoted object keys because that position is unambiguous. Function names and bare helper references resolve before execution. There is no function overloading by arity, implicit recursion capture or dynamic code generation. A malformed program is rejected rather than executed as another language.