{"modulePath":"github.com/OpenMachineLabs/openmachine","version":"v0.3.2","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package daemon\n\nPackage daemon is Open Machine's device-side Code integration.\n\n## Constants\n\n```go\nconst GitHubRouting = \"github-routing\"\n```\nGitHubRouting is the folder of sessions' Git routing in the state.\n\n```go\nconst ProofsKey = \"openmachineProofs\"\n```\nProofsKey names, under credential.\\\u003cbroker\u003e, the directory of Full Access proofs.\n\n## Variables\n\n```go\nvar (\n\t// ErrNoAuthority reports that Cloud grants this device no Code authority.\n\tErrNoAuthority = errors.New(\"native: this device has no Code authority\")\n\t// ErrUnavailable reports that Cloud cannot be reached: existing Code\n\t// sessions continue, but nothing new is admitted until it can.\n\tErrUnavailable = errors.New(\"native: Cloud is unavailable; existing Code sessions only\")\n)\n```\n\n```go\nvar (\n\tHoldEvery     = 2 * time.Minute  // a held session is posted again\n\tHoldGrace     = time.Minute      // a session outlasts its last dial\n\tHoldWait      = 5 * time.Second  // a connected dial waits for its session's post\n\tRequestsEvery = 10 * time.Second // the person's requests are read at most\n)\n```\nThe pace of a person's GitHub on team machines; tests shorten them.\n\n```go\nvar CloudClient = \u0026http.Client{Transport: CloudTransport(nil, nil)}\n```\nCloudClient is the client of every request this device makes to Cloud: enrollment, the Code lease and the GitHub broker's proofs. It has no timeout, since a lease's WebSocket lives on; each request bounds itself with its context.\n\n```go\nvar CoreRead = 10 * time.Minute\n```\nCoreRead is how often a Core that answered is asked again; tests shorten it.\n\n```go\nvar ErrDeviceChanged = errors.New(\"native: this computer moved to another device\")\n```\nErrDeviceChanged ends a daemon whose computer a sign-in moved to another device.\n\n```go\nvar ErrOffline = errors.New(\"native: this computer is disconnected from Open Machine\")\n```\nErrOffline reports that this computer is offline: Desktop is Disconnected, signed out or cannot be read safely, or the Connector is stopped, revoked or registered otherwise. Offline admits no SSH and closes every SSH connection into or out of this computer.\n\n```go\nvar ErrUnreachable = errors.New(\"offline or unreachable\")\n```\nErrUnreachable is in dial's error for a machine that is offline.\n\n```go\nvar HardwareID = func() func(dir string) (string, error) {\n\tvar mu sync.Mutex\n\tids := map[string]string{}\n\treturn func(dir string) (string, error) {\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\tif ids[dir] == \"\" {\n\t\t\tread, err := readHardwareID(dir)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tids[dir] = read\n\t\t}\n\t\treturn ids[dir], nil\n\t}\n}()\n```\nHardwareID returns this machine's hardware ID: its IOPlatformUUID on macOS; on Linux the file hardware-id in the Connector's state directory dir if it exists, else /etc/machine-id. It is read once per process and directory, retried until read, and never leaves this machine. Tests replace it.\n\n```go\nvar JoinTimeout = time.Minute\n```\nJoinTimeout bounds each start of the network node; tests shorten it.\n\n```go\nvar MaxDaemonLog int64 = 1 \u003c\u003c 20\n```\nMaxDaemonLog bounds daemon.log; one earlier file, daemon.log.1, is kept. Tests shorten it.\n\n```go\nvar StartMove = func(secret string) bool { return startOM(\"move\", secret) }\n```\nStartMove starts \\`om move\\` as StartUpdate starts an update: the move makes this daemon exit for the device it registers. The move's secret goes to its standard input, never to a command line or the environment. Tests replace it.\n\n```go\nvar StartUpdate = func() bool { return startOM(\"update\", \"\") }\n```\nStartUpdate starts this binary's \\`om update\\` in its own session: the update restarts this daemon and must outlive it. It reports whether it started. Tests replace it.\n\n```go\nvar StillEvery = time.Minute\n```\nStillEvery is how often a wait says it still waits, so that an agent's silence timeout never ends it and an agent whose command was stopped learns why; tests shorten it.\n\n## Functions\n\n```go\nfunc App(pid int, process func(pid int) (parent int, name string, args []string)) string\n```\nApp names the app that ran the ssh whose process is pid: the nearest of up to 8 processes, from ssh's parent upward, whose name, or the last path segment of its first or second argument, matches an app; else Terminal. process returns a process's parent, name and arguments.\n\n```go\nfunc AutoUpdate(ctx context.Context, state string, refused \u003c-chan struct{}, open func() bool, start func(),\n\tfirst, daily, every time.Duration)\n```\nAutoUpdate asks for updates of a headless installation until ctx ends: after first and then once each daily, and at once when refused receives, Cloud having refused this om as too old, then at most once each every while it does. A request calls start when auto\\_update in state's headless.json, read then, is on and open reports no SSH connection; while one is open it waits and looks again each every. A Mac has no headless.json, so it never asks.\n\n```go\nfunc Clean(s string) string\n```\nClean makes a name from a machine's program safe to show: white space collapsed, control and format characters removed, the ends trimmed and at most 40 code points kept.\n\n```go\nfunc CloudTransport(dial func(ctx context.Context, network, addr string) (net.Conn, error), roots *x509.CertPool) *http.Transport\n```\nCloudTransport dials with Happy Eyeballs, as Go does by default, and, when the connection or its TLS handshake fails, dials once more over IPv4 only. A VPN that tunnels IPv6 without forwarding it accepts the IPv6 TCP connection and then drops it, so Happy Eyeballs picks it and never tries IPv4. Nothing of the request is written before the handshake completes, so the second dial never resends one. Like the Connector, it never takes a proxy from the environment. dial and roots replace the system dialer and certificate roots when not nil.\n\n```go\nfunc GitCredential(args []string, stdin io.Reader, stdout, stderr io.Writer) int\n```\nGitCredential is om git-credential, a session's only Git credential helper for its broker (gitcredentials(7)). get exchanges the session's capability for one command's credential for the remote's repository; store and erase do nothing, so the credential lives only in git's memory. A refusal stops git from asking anyone else.\n\n```go\nfunc GitHub(args []string, stdout, stderr io.Writer) int\n```\nGitHub is om github: a session's fixed pull request and CI operations, through its broker and the account's GitHub connection in Cloud. There is no merge, workflow dispatch, release or other call, and no gh or token.\n\n```go\nfunc Include(home, dir string) error\n```\nInclude adds one line, an Include of the generated ssh\\_config in the daemon's state dir, at the top of ~/.ssh/config under home, once: it creates ~/.ssh (0700) and the file (0600) if missing, writes atomically, keeps every other byte and the file's mode, and records in dir that it is done, so it never touches the file again and a user who removes the line keeps it removed. A ~/.ssh/config that is a symbolic link, as dotfile managers make, is left untouched for good; one that is not this user's regular file is an error, tried again with a later lease. Nothing is checked for conflicts or ever undone.\n\n```go\nfunc LogDiscarded(dir string)\n```\nLogDiscarded sends the daemon's log to daemon.log in its state directory dir when its standard error is closed or /dev/null, as launchd leaves a Mac's agent, so why it is not connected can be read. A supervisor that keeps the log, as systemd or om's shell kind does, keeps it alone.\n\n```go\nfunc PeerUID(proc []byte, peer, local netip.AddrPort) (uint32, bool)\n```\nPeerUID finds, in Linux's /proc/net/tcp or tcp6, the socket connected from peer to local, and returns the user that owns it.\n\n```go\nfunc PinnedClient(pin string, timeout time.Duration) *http.Client\n```\nPinnedClient returns a client that completes a TLS handshake only with a server holding the key pin names, and checks nothing else of its certificate, as Git does with the routing's pinnedPubkey and sslVerify false. It never sends a request in plain text.\n\n```go\nfunc Probe(addr netip.AddrPort) (web bool, title string, again bool)\n```\nProbe tells a web page from another program listening at addr. A program that speaks first is not one. Otherwise it sends GET / without a Host line, which Redis closes on, and once more with one after a 403, which Vite 5 and 6 and webpack-dev-server give without it. 3xx, or HTML with 2xx, 401 or 403, is a page; a page's title comes from a 2xx answer, after at most 2 redirects to this port's address. again reports an answer late or with a 5xx, also a redirect's, as from a program still starting. It dials the loopback addresses that reach addr, never a name, which a resolver could send elsewhere: both for any address, as a dual-stack socket may be reachable on either.\n\n```go\nfunc ProcNet(b []byte) map[string]netip.AddrPort\n```\nProcNet reads the sockets in LISTEN state from Linux's /proc/net/tcp or tcp6, by inode.\n\n```go\nfunc Proxy(state, host string, stdin io.Reader, stdout io.Writer) error\n```\nProxy is the ProxyCommand: it asks the local daemon, over its owner-only socket, for an SSH stream to host and copies it between stdin and stdout. It starts no network node of its own; stdout carries SSH bytes only. Before ssh's bytes it tells the target which app ran ssh, in a line an older target's SSH server skips.\n\n```go\nfunc ReadApp(r *bufio.Reader) string\n```\nReadApp reads the line a source's om proxy sends before SSH, OM-APP and the app's name, from a reader whose 64-byte buffer bounds it: the name, or \"\" for a line that is not one. A stream that starts otherwise is left unread.\n\n```go\nfunc RedactNetwork(line, home, authKey string) string\n```\nRedactNetwork removes from a network log line what must not reach a log: what redact hides, the node's registration key, any other key of that form and URL queries; and writes home as ~, so a log can be shared.\n\n```go\nfunc Run(ctx context.Context, core Core) error\n```\nRun runs the daemon of the user whose HOME is core.Home until ctx ends. It waits for the device identity, which sign-in creates, then joins the network once for that device and reuses its node and host key from then on. Its only OS TCP ports are the local entry to machines' web pages and each opened page's own, on 127.0.0.1 and \\[::1]. Neither a missing identity nor state that needs recovery, which a restart cannot fix, ends it: a supervisor never restarts it in a loop. It returns ErrDeviceChanged when a sign-in moves this computer to another device, also during recovery, so its supervisor starts it again for that device.\n\n```go\nfunc SendsScript(line string) bool\n```\nSendsScript reports whether line runs what the connection's input holds: anywhere in it, a pipe's included, a shell given no -c and no file, su given no -c, or one of starts given nothing to run, such as bash -euo pipefail, cd /srv \u0026\u0026 bash -s or sudo -i.\n\n```go\nfunc ServeModels(ch io.ReadWriter, list []Service, forwarded func(port int))\n```\nServeModels answers the one HTTP request of a models channel from list, this machine's services: GET /v1/models with their models; an inference POST by passing it to the server of the model its body names, once forwarded is told that server's port, and passing the answer back as it comes. Anything else is {\"error\":{\"message\":…}}. Every answer says Connection: close.\n\n```go\nfunc Sign(key ed25519.PrivateKey, origin, method, path, challengeID, challenge string, body []byte) string\n```\nSign returns the om-device-v1 proof Cloud verifies: the device key over the origin, method, path, challenge and SHA-256 of the exact body bytes.\n\n```go\nfunc StateDir(home string) string\n```\nStateDir is the daemon's private state under home. Core denies it, and the Connector's state beside it, to restricted sessions, but for GitHubRouting, which they read.\n\n## Types\n\n```go\ntype Approval struct {\n\tTeam struct {\n\t\tSlug string `json:\"slug\"`\n\t\tName string `json:\"name\"`\n\t} `json:\"team\"`\n\tState string `json:\"state\"`\n}\n```\nApproval is a team that has not approved this computer, so that its machines refuse it. It only says why: admission never reads it.\n\n```go\ntype Authority struct {\n\t// contains filtered or unexported fields\n}\n```\nAuthority holds this device's Code lease. A new Code admission needs a current lease from a live Cloud session. Losing Cloud, or a lease running out, only stops new admissions: what was admitted keeps running until an applied lease closes it. Each lease runs from when its renewal was sent, so a late reply never extends it, and replies apply in the order sent. A changed lease admits nothing new until it is applied, and is then acknowledged.\n\nEach renewal reports whether this computer can serve Code, Core's version, the modes Core can enforce and the machine's listening programs. Leases also carry the account view, which is held in memory only.\n\n```go\nfunc NewAuthority(origin, deviceID string, key ed25519.PrivateKey, d Device, log *Log, client *http.Client) *Authority\n```\nNewAuthority returns the Code authority of the device registered under deviceID with key, at the Cloud origin, served by d. It starts log at the first lease of a Cloud that takes it, and sends it over every presence.\n\n```go\nfunc (a *Authority) Approval() *Approval\n```\nApproval returns the last lease's approval, if any.\n\n```go\nfunc (a *Authority) Core(v string, policies map[string]string)\n```\nCore records Core's version and the modes it can enforce, renewing at once when either changes. A version that is not 1 to 32 letters, digits, '.', '+' or '-', or policies that are not the three modes' states, are reported as unknown.\n\n```go\nfunc (a *Authority) Current() *Lease\n```\nCurrent returns the lease that admits new Code sessions now, else nil.\n\n```go\nfunc (a *Authority) Devices() []ViewDevice\n```\nDevices returns the machines of the last lease's view.\n\n```go\nfunc (a *Authority) GitHub(view json.RawMessage)\n```\nGitHub sets the view's github: the person's waiting GitHub requests and new notices.\n\n```go\nfunc (a *Authority) Joining(reason string)\n```\nJoining records why the last step toward listening failed, as a status reason; \"\" while the next step runs without one.\n\n```go\nfunc (a *Authority) Listening()\n```\nListening records that the SSH host listens on the private network.\n\n```go\nfunc (a *Authority) Person() bool\n```\nPerson reports whether the last lease's account is a person's, not a team's.\n\n```go\nfunc (a *Authority) Recheck() error\n```\nRecheck reads the device's Admission, renews at once when that changes whether this computer can serve Code, and returns it.\n\n```go\nfunc (a *Authority) Refused() \u003c-chan struct{}\n```\nRefused receives after each connection attempt Cloud refused as too old.\n\n```go\nfunc (a *Authority) Run(ctx context.Context)\n```\nRun holds the lease until ctx ends, reconnecting to Cloud as needed.\n\n```go\nfunc (a *Authority) Services(list []Service)\n```\nServices records this machine's listening programs, renewing at once when they change.\n\n```go\nfunc (a *Authority) Status() string\n```\nStatus reports whether this computer is connected to Open Machine Code: \"\" when it is, else the first reason it is not: offline; joining, or while the network is not joined why the last step failed (see joinReason); update\\_required (Cloud refused this om as too old); cloud\\_unavailable or no\\_authority.\n\n```go\nfunc (a *Authority) View() ([]byte, \u003c-chan struct{})\n```\nView returns the account view as one JSON line and a channel closed when it may have changed. Without a session that holds a lease the last values stay, and every device's state is unknown.\n\n```go\nfunc (a *Authority) Wait(ctx context.Context) (*Lease, error)\n```\nWait admits a new Code session from the lease held here, without contacting Cloud, while it lasts. Without one it fails at once if Cloud is unavailable; otherwise it asks Cloud for a renewal, as after a wake, and waits up to ctx.\n\n```go\ntype Broker struct {\n\tURL string // https://127.0.0.1:PORT\n\tPin string // sha256//BASE64 of its key, Git's http.pinnedPubkey form\n\t// contains filtered or unexported fields\n}\n```\nBroker is the target's Code GitHub broker: a loopback endpoint for the Git commands and om github calls of admitted SSH sessions, never the daemon's management socket. A session holds a capability in its environment; om git-credential exchanges it for one command's credential, for one repository and the actions the session's policy allows there. Cloud adds the account's token: neither the broker nor the session ever holds one.\n\nA restricted sandbox can read other processes' environments (kern.procargs2), which Seatbelt cannot deny. So a Full Access session's capability, the only one that writes, also needs a proof the broker keeps in a file named after it under proofs, in the daemon's state, which Core denies to restricted work. om reads it there, outside any sandbox, from the directory its own routing names, never from a reply: whatever answers at the broker's port gets nothing else.\n\nAny local process, a restricted sandbox too, may listen on the port a stopped broker freed, where detached jobs' routing still points. So the broker serves TLS with a key made in memory each time it starts, never stored, and every client pins it: Git through its routing, om by the same routing. Whatever else answers there, a later broker too, fails the handshake before a request is sent, and Git fails closed.\n\nA session's routing is a file Git includes at every command, named in its environment, so that it follows the source's allow while the session lasts: the file exists only while that allow has github. Restricted work may read the routing folder, never write it; a file holds no secret.\n\n```go\nfunc NewBroker(origin, deviceID string, key ed25519.PrivateKey, client *http.Client, proofs, routes string) (*Broker, error)\n```\nNewBroker starts the broker of the device registered under deviceID with key, at the Cloud origin, keeping Full Access sessions' proofs and pushes that wait for an approval in the owner-only directory proofs, emptied first, and sessions' routing in the directory routes, whose files are removed. routes itself stays: a restricted lifetime started earlier holds it.\n\n```go\nfunc (b *Broker) Close() error\n```\nClose stops the broker.\n\n```go\nfunc (b *Broker) Environment(capability string) map[string]string\n```\nEnvironment is the environment of the session whose capability it is: the broker, the capability and the absolute path of the session's routing, which Git includes in every command.\n\n```go\nfunc (b *Broker) Open(s GitSession) (string, func())\n```\nOpen registers an admitted session, writing its routing if its source's allow has github, and returns its capability, and a function that ends the session's GitHub access, called when the session ends.\n\n```go\nfunc (b *Broker) Reroute()\n```\nReroute writes or removes each session's routing as its source's allow now has github or not.\n\n```go\nfunc (b *Broker) ServeHTTP(w http.ResponseWriter, r *http.Request)\n```\n\n```go\ntype CommandRule struct {\n\tTitle string    `json:\"title\"`\n\tNote  string    `json:\"note\"`\n\tMatch []Pattern `json:\"match\"`\n\tPaths []string  `json:\"paths\"`\n}\n```\nCommandRule stops a line one of whose commands its patterns hold, or that touches its paths at the level read.\n\n```go\ntype Core struct {\n\tPython string   // Core's interpreter\n\tArgs   []string // optional --config and --state-dir for Core\n\tHome   string   // HOME for Core, so its control paths cover this daemon's state\n}\n```\nCore runs Core's access launcher, the one boundary through which Code work starts: Go checks Cloud authority, and Core checks paths and confines the command.\n\n```go\nfunc (c Core) Folders(request []byte) (json.RawMessage, error)\n```\nFolders runs Core's Workspace folder check in its own Core process, with request on its stdin, for at most 120 seconds, and returns the JSON object Core writes: the canonical folders or Core's refusal. Anything else, such as more than 64 KiB or a failed launcher, is an error.\n\n```go\ntype Device interface {\n\t// Apply closes the connections l no longer permits, with their channels\n\t// and forwards, before it returns; Lease.Target nil closes them all. It\n\t// ends no process: Code is a connection layer.\n\tApply(l Lease)\n\t// Admission reports whether this computer is online: nil, or why not.\n\tAdmission() error\n\t// Folders is this machine's own check of l's Workspace folders, once l is\n\t// applied: nil, or its refusal. It may take as long as Core's check.\n\tFolders(l Lease) *Refusal\n\t// Update starts this machine's own update now, as its owner asked in the\n\t// Console, and reports whether it started.\n\tUpdate() bool\n\t// Move starts this machine's move to another account of the person who\n\t// asked for it in the Console, with the one-time secret Cloud issued, and\n\t// reports whether it started.\n\tMove(secret string) bool\n\t// Changed is told each change Cloud announces, before the lease that follows.\n\tChanged()\n}\n```\nDevice is the device side of an Authority.\n\n```go\ntype Discovery struct {\n\t// contains filtered or unexported fields\n}\n```\nDiscovery remembers each port and process it probed, so each is probed once, or up to 3 times in a row of passes while it answers late or with a 5xx, and reads each model server's list again every pass, as it asks one that is not ready yet.\n\n```go\nfunc (d *Discovery) Pass(ls []Listener) []Service\n```\nPass returns the services of ls, in its order, probing at most 8 new or unsettled ports and processes at once; the others wait for the next pass. Beside them it asks each model server it knows, and each program whose models are still to come, again. Of the models it returns the first 200 whose JSON fits 32 KiB, each id once.\n\n```go\ntype FileRule struct {\n\tTitle string   `json:\"title\"`\n\tNote  string   `json:\"note\"`\n\tLevel string   `json:\"level\"`\n\tPaths []string `json:\"paths\"`\n}\n```\nFileRule stops a line one of whose commands touches its paths at its level, none or read.\n\n```go\ntype GitSession struct {\n\tSource              string\n\tSourceGrantRevision int64\n\tTargetGrant         string\n\tTargetGrantRevision int64\n\tPolicyRevision      int64\n\tMode                string // read_only, workspace or full_access\n\tVisit               string // the session's connection in the log, which Cloud's records of its Git name\n\tClient              string // the om the session runs as its credential helper\n\tLive                func() error\n\tGitHub              func() bool\n\tDone                \u003c-chan struct{}\n}\n```\nGitSession is what one admitted SSH session may do with GitHub: the binding and policy it was admitted under, and the om it runs. Live reports whether it may start new GitHub work, and GitHub whether its source's allow has github now; Done closes when its connection ends, which stops its requests in flight.\n\n```go\ntype Holds struct {\n\t// contains filtered or unexported fields\n}\n```\nHolds keeps the person's GitHub session open on each team's machine this computer dials, through post: an opening post alongside the first dial, again every HoldEvery while a dial lasts, and a closing one once none has for HoldGrace. After held: false it posts nothing for that machine until Changed.\n\n```go\nfunc NewHolds(post func(target string, open bool) (bool, error)) *Holds\n```\nNewHolds returns Holds that post through post; Run paces them.\n\n```go\nfunc (h *Holds) Changed()\n```\nChanged lifts every held: false and posts again for each such machine a dial lasts to.\n\n```go\nfunc (h *Holds) Dial(target string) (\u003c-chan struct{}, func())\n```\nDial counts a dial to the team's machine target until end. The channel closes when its session's post in flight, if any, has ended.\n\n```go\nfunc (h *Holds) Run(ctx context.Context)\n```\nRun posts what is due each second until ctx ends.\n\n```go\ntype Host struct {\n\tDeviceID string   `json:\"device_id\"`\n\tNodeKey  string   `json:\"node_key\"`\n\tKey      string   `json:\"key\"`     // OpenSSH public key\n\tUser     string   `json:\"user\"`    // the OS user that runs Open Machine there\n\tAliases  []string `json:\"aliases\"` // the first is canonical\n}\n```\nHost is a device this one may connect to, at its registered SSH host.\n\n```go\ntype Identity struct {\n\tOrigin, DeviceID, PrincipalID string\n\tKey                           ed25519.PrivateKey\n\t// contains filtered or unexported fields\n}\n```\nIdentity is this device's registration, owned by the Python Connector. Code only reads it: a missing or unsafe identity means sign-in or recovery is needed, never a new enrollment.\n\n```go\nfunc ReadIdentity(dir string) (*Identity, error)\n```\nReadIdentity reads the device in use in the Connector's state directory: its binding and the 32-byte Ed25519 seed of the key file it names, which must be that key and bound to this machine. Anything else means this computer is not ready: it has yet to sign in.\n\n```go\nfunc (id *Identity) Admission() error\n```\nAdmission reports whether this computer is online, read the way the Connector reads it and never written: still this registration and not revoked, Desktop's remote-access intent on, and the Connector enabled. It is nil or ErrOffline.\n\n```go\ntype Lease struct {\n\tEpoch    int64    `json:\"epoch\"`    // the Code presence it was issued to\n\tRevision string   `json:\"revision\"` // identifies Target, Sources and Hosts\n\tTarget   *Target  `json:\"target\"`   // nil: the device has no Code authority, and all its Code connections close\n\tSources  []Source `json:\"sources\"`  // the devices that may connect to this one\n\tHosts    []Host   `json:\"hosts\"`    // the devices this one may connect to\n}\n```\nLease is this device's Code authority from Cloud.\n\n```go\ntype Listener struct {\n\tAddr netip.AddrPort\n\tPID  int\n\tName string\n\tExe  string // its executable, read on macOS only\n}\n```\nListener is a TCP socket the OS lists in LISTEN state, with the process holding it: PID 0 and no name when that is unreadable.\n\n```go\nfunc Listed(ls []Listener, first, last int) []Listener\n```\nListed returns the listeners a pass lists, one per port by its lowest PID, the lowest 64 ports: those bound where localhost reaches them, other than om's own, Apple's programs, ports below 1024 but 80 and 443, and the OS's ephemeral range from first to last, where editors' and kernels' random ports live.\n\n```go\nfunc Lsof(b []byte) []Listener\n```\nLsof reads \\`lsof -F pcn\\`'s output: a p line starts each process, c names it and n is each socket's address, \\* for any.\n\n```go\ntype Local struct {\n\t// contains filtered or unexported fields\n}\n```\nLocal is this computer's entry to the web pages on the machines it reaches. [http://localhost](http://localhost):\\\u003centry\u003e/\\\u003calias\u003e/\\\u003cport\u003e gives the page a port of its own on this computer and sends the browser there: [http://127.0.0.1](http://127.0.0.1):\\\u003cthat port\u003e/ is localhost:\\\u003cport\u003e on that machine, through one OM SSH connection for each page, once the person has confirmed the page in this browser. Of the names that reach this computer, only localhost and its addresses are ones no browser sends to a system proxy, so pages differ by port; 127.0.0.1 keeps their cookies apart from this computer's own programs at localhost. At the entry's port it is also the one address of the AI models this computer reaches, through one OM SSH connection for each machine.\n\n```go\nfunc NewLocal(o Opener, deviceID, port string) *Local\n```\nNewLocal returns the entry of the device deviceID, which listens on port.\n\n```go\nfunc (l *Local) Serve(ctx context.Context, port string)\n```\nServe serves l on 127.0.0.1 and \\[::1], at its port and at each page's, until ctx ends. An entry address it cannot bind is tried again every 30 seconds and logged once; a page whose port is taken gets another one when it is opened next.\n\n```go\nfunc (l *Local) ServeHTTP(w http.ResponseWriter, r *http.Request)\n```\n\n```go\ntype Lock struct {\n\tTitle string     `json:\"title\"`\n\tNote  string     `json:\"note\"`\n\tAllow [][]string `json:\"allow\"`\n}\n```\nLock runs only the commands that begin with an allowed one.\n\n```go\ntype Log struct {\n\t// contains filtered or unexported fields\n}\n```\nLog is a machine's own record of who connected to it and what they ran: signed lines in a queue on disk, each named by its place, sent to Cloud and deleted once Cloud has them. It records nothing until it is started.\n\n```go\nfunc OpenLog(dir, device string, key ed25519.PrivateKey) *Log\n```\nOpenLog returns the log of device kept in dir. A queue made by an earlier run records and sends at once.\n\n```go\nfunc (l *Log) Close(reason string, lease *Lease)\n```\nClose ends, for reason, each connected connection that lease no longer permits: every one when lease is nil, as the machine goes offline.\n\n```go\nfunc (l *Log) Enter(lease *Lease, s Source, app string) *Visit\n```\nEnter records a transport from source s through app, admitted under lease: it joins that source and app's open connection, after ending one admitted under another binding, or opens one. The first admitted transport of a connection is its connect. A source limited to the AI models connects with that access, in no folder, whatever the machine's mode.\n\n```go\nfunc (l *Log) Expire(now time.Time)\n```\nExpire ends each connection that has had no transport for the 10 minutes before now.\n\n```go\nfunc (l *Log) Frame() (*LogFrame, \u003c-chan struct{})\n```\nFrame returns the frame to send next, from the first place Cloud has not confirmed, or nil when it has them all, and a channel closed when a record is written or Cloud confirms one.\n\n```go\nfunc (l *Log) Logged(queue string, through int64)\n```\nLogged takes Cloud's confirmation of every place of queue through n, and deletes each file it covers but the one appended to.\n\n```go\nfunc (l *Log) Refuse(source, app, reason, message string)\n```\nRefuse records a transport from source through app that was not admitted, in that source and app's connection, opening one if there is none.\n\n```go\nfunc (l *Log) Start()\n```\nStart makes the queue, once a Cloud that takes its frames is known.\n\n```go\ntype LogFrame struct {\n\tType    string            `json:\"type\"` // log\n\tQueue   string            `json:\"queue\"`\n\tFrom    int64             `json:\"from\"`\n\tRecords []json.RawMessage `json:\"records\"`\n}\n```\nLogFrame is the records a machine sends next: the queue's lines from the place From, each as stored, or null for one that is no record.\n\n```go\ntype Model struct {\n\tID   string `json:\"id\"`\n\tChat bool   `json:\"chat\"`\n}\n```\nModel is an AI model a model server lists, and whether it can chat.\n\n```go\ntype Opener interface {\n\t// Lease returns the lease new work starts under, once this computer has\n\t// joined the private network, or why it is not ready.\n\tLease() (*Lease, error)\n\t// Devices returns the machines of the last lease's view.\n\tDevices() []ViewDevice\n\t// Approval returns the last lease's approval, if any.\n\tApproval() *Approval\n\t// Dial opens an OM SSH stream to the machine alias names, for app, that\n\t// going offline closes. ErrUnreachable reports a machine that is offline.\n\tDial(alias, app string) (net.Conn, error)\n\t// Services returns this computer's listening programs, with their models.\n\tServices() []Service\n\t// Key returns the 32-byte key the cookies of confirmed pages are made with.\n\tKey() ([]byte, error)\n\t// Pages returns the pages given a port on this computer, the one opened\n\t// last first, as SavePages last kept them.\n\tPages() ([]Page, error)\n\tSavePages([]Page) error\n}\n```\nOpener is the daemon side of a Local: this computer's lease, its view of the account's machines and the OM SSH streams out of it.\n\n```go\ntype Page struct {\n\tPage string `json:\"page\"` // alias:port\n\tPort int    `json:\"port\"`\n}\n```\nPage is a machine's web page with its port on this computer.\n\n```go\ntype Pattern struct {\n\tW    [][]string `json:\"w\"`    // tokens, each a list of alternatives\n\tInto []string   `json:\"into\"` // when not nil, what the command's output goes into matches one\n\tNot  bool       `json:\"not\"`  // an exception\n}\n```\nPattern holds a command whose name matches its first token and whose words match each other one.\n\n```go\ntype Record struct {\n\tQueue       string `json:\"queue\"`\n\tN           int64  `json:\"n\"`\n\tAt          string `json:\"at\"`\n\tType        string `json:\"type\"` // connect, disconnect, refuse, start, end, block, forward or boot\n\tDevice      string `json:\"device\"`\n\tVisit       string `json:\"visit,omitempty\"`\n\tSource      string `json:\"source,omitempty\"`\n\tSession     string `json:\"session,omitempty\"`\n\tApp         string `json:\"app,omitempty\"`\n\tAccess      string `json:\"access,omitempty\"`\n\tFolder      string `json:\"folder,omitempty\"`\n\tGrant       int64  `json:\"grant,omitempty\"`\n\tSourceGrant int64  `json:\"source_grant,omitempty\"`\n\tPolicy      int64  `json:\"policy,omitempty\"`\n\tReason      string `json:\"reason,omitempty\"`\n\tLast        string `json:\"last,omitempty\"`\n\tStage       string `json:\"stage,omitempty\"`\n\tMessage     string `json:\"message,omitempty\"`\n\tKind        string `json:\"kind,omitempty\"`\n\tTerminal    int    `json:\"terminal,omitempty\"`\n\tCommand     string `json:\"command,omitempty\"` // only where the account records commands\n\tScript      string `json:\"script,omitempty\"`  // as Command\n\tCut         int    `json:\"cut,omitempty\"`\n\tExit        *int   `json:\"exit,omitempty\"`\n\tSignal      string `json:\"signal,omitempty\"`\n\tError       string `json:\"error,omitempty\"`\n\tRule        string `json:\"rule,omitempty\"`\n\tHost        string `json:\"host,omitempty\"`\n\tPort        int    `json:\"port,omitempty\"`\n\tVersion     string `json:\"version,omitempty\"`\n\tSig         string `json:\"sig\"`\n}\n```\nRecord is one record of a machine's log: its fields in the order they are signed, the absent ones left out.\n\n```go\nfunc (r Record) Sign(key ed25519.PrivateKey) string\n```\nSign returns r's signature: key over om-log-v1 and, for each present field in order, its name, its length in bytes and its value.\n\n```go\ntype Refusal struct {\n\tCode  string `json:\"code\"`\n\tIndex int    `json:\"index\"`\n}\n```\nRefusal is a machine's refusal of the Workspace folder at Index of its lease, with Core's code.\n\n```go\ntype Rules struct {\n\tHead     string        `json:\"head\"` // Blocked by Open Machine on \u003cmachine\u003e\n\tFoot     string        `json:\"foot\"` // who can change the rules\n\tCommands []CommandRule `json:\"commands\"`\n\tFiles    []FileRule    `json:\"files\"`\n\tWrites   []Pattern     `json:\"writes\"` // the commands that change the files they name\n\tUses     []Pattern     `json:\"uses\"`   // those that may name a No access file\n\tCopies   []string      `json:\"copies\"` // those that change only the last file they name\n\tLock     *Lock         `json:\"lock\"`   // nil unless only listed commands run\n}\n```\nRules are what the target's account blocks on it. om checks every new session against them before Core runs it.\n\n```go\nfunc (r *Rules) Check(kind, line, home string) *Stop\n```\nCheck returns what stops a session of kind with line, its exec command, on the machine whose user's home is home, or nil. A shell, sftp or forward is stopped only by the lock; nil rules stop nothing.\n\n```go\ntype Service struct {\n\tPort   int            `json:\"port\"`\n\tName   string         `json:\"name\"`\n\tWeb    bool           `json:\"web\"`\n\tModels []Model        `json:\"models,omitzero\"`\n\tAddr   netip.AddrPort `json:\"-\"` // where it listens: what a request for one of its models dials\n}\n```\nService is one program listening on this machine, as renewals report it: a model server with its models, which may be none.\n\n```go\ntype Source struct {\n\tDeviceID      string   `json:\"device_id\"`\n\tNodeKey       string   `json:\"node_key\"`\n\tGrantRevision int64    `json:\"grant_revision\"`\n\tAllow         []string `json:\"allow\"`           // what it gets besides its sessions: github, their GitHub routing; models, this machine's AI models\n\tLimit         string   `json:\"limit,omitempty\"` // read_only: its sessions run Read only, whatever the target's policy; models: it gets the AI models only\n\tHome          string   `json:\"home,omitempty\"`  // the key of its owner's sandbox home here, for Core; \"\" for the machine's own\n}\n```\nSource is a device that may connect to this one. Its Code connections admitted under another grant revision or limit close, as do those of a source no longer listed.\n\n```go\ntype Stop struct {\n\tRule    string // the title of the rule or the lock; \"\" for a line not checked\n\tLock    bool\n\tMessage string // the lines its stderr gets\n}\n```\nStop is what stops a session: a rule, the lock, or a line too long or too nested to check.\n\n```go\nfunc (s *Stop) Error() string\n```\n\n```go\ntype Target struct {\n\tGrantID       string          `json:\"grant_id\"`\n\tGrantRevision int64           `json:\"grant_revision\"`\n\tPolicy        json.RawMessage `json:\"policy\"` // Cloud's device policy, or null when unreadable\n\tRules         *Rules          `json:\"rules\"`  // what the account blocks here; nil from a Cloud without rules\n\t// Record is null, or {\"notice\": …} where the account records the commands\n\t// run here; a Cloud without logs sends none.\n\tRecord json.RawMessage `json:\"record,omitempty\"`\n}\n```\nTarget is this device's own authority. Code connections admitted under another grant revision or policy close; a change of Rules closes nothing, and the next session is checked under the lease current then.\n\n```go\ntype ViewDevice struct {\n\tDeviceID    string  `json:\"device_id\"`\n\tName        string  `json:\"name\"`\n\tMode        *string `json:\"mode\"`\n\tAlias       *string `json:\"alias\"` // its display alias, else its canonical one, else nil\n\tState       string  `json:\"state\"`\n\tLastSeenAt  *int64  `json:\"last_seen_at\"`\n\tCoreVersion *string `json:\"core_version\"`\n\tTeam        *struct {\n\t\tSlug string `json:\"slug\"`\n\t\tName string `json:\"name\"`\n\t} `json:\"team,omitempty\"` // of a team's machine\n}\n```\nViewDevice is a device as the account view lists it: one of the account, or a team's machine this device's owner reaches. It is display data: nothing is admitted or closed by it.\n\n```go\ntype Visit struct {\n\t// contains filtered or unexported fields\n}\n```\nVisit is one open connection: one source's app on this machine, from its first transport until it has had none for 10 minutes, or a lease or going offline ends it. A nil Visit records nothing.\n\n```go\nfunc (v *Visit) ID() string\n```\nID returns v's ID, \"\" for a connection that is not recorded.\n\n```go\nfunc (v *Visit) Leave()\n```\nLeave records that one of v's transports closed.\n\n```go\nfunc (v *Visit) Notice(kind, text string) string\n```\nNotice returns what a session of kind is told before it runs, where the account records commands and tells people so with text: each shell, and an exec once for each text. SFTP runs no command.\n\n```go\nfunc (v *Visit) Refuse(stage, reason, message string)\n```\nRefuse records what om refused v at stage, transport or channel, once for each stage and reason.\n\n```go\nfunc (v *Visit) Write(r Record) error\n```\nWrite records r in v, durably before it returns. Its texts are made valid UTF-8, a command and a script are redacted, and each is cut to its bound.\n\n","path":"github.com/OpenMachineLabs/openmachine/daemon","name":"daemon","synopsis":"Package daemon is Open Machine's device-side Code integration.","isRedistributable":true}
