package stdio import ( "reflect" "regexp" "sync" "unsafe" ) // Unproven is the caller of a call the runtime named no caller for: one that arrived on the subject that names // none, or from a runtime that names none (novox/hq issue 365). Said as a word, never left empty, so a record // shows it was not proven. const Unproven = "unproven" // MetaCaller is where in a `tools/call`'s `_meta` the runtime names the caller: the bus user that published the // call, which the runtime takes from the subject the call arrived on — that subject's last token, which the // bus lets each user publish with its own name alone (novox/hq issue 365, by ADR 0259 §3's precedent). The // runtime writes `_meta`; a caller writes only `arguments`, so no caller can name another. const MetaCaller = "mesh/caller" // busUser is the shape of a bus user's name: `.`, `person.`, `controller` — names whose // parts are safe in a subject. Anything else the runtime named is not a caller and reads as Unproven. var busUser = regexp.MustCompile(`^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$`) // calls holds the caller of every call while its tool runs, by the arguments map that call was handed. var calls sync.Map // unsafe.Pointer → string func argsKey(args map[string]any) unsafe.Pointer { return reflect.ValueOf(args).UnsafePointer() } // CallerOf is who called the tool that was handed args, as the runtime proved it: the bus user that // published the call, or Unproven. Read from the runtime, never from the arguments' contents — a `caller` // argument names nobody. Valid while the tool runs; arguments no call was handed have no caller. func CallerOf(args map[string]any) string { if args == nil { return Unproven } if c, ok := calls.Load(argsKey(args)); ok { return c.(string) } return Unproven } // callerIn is the caller a `tools/call`'s `_meta` names, or Unproven. func callerIn(meta map[string]any) string { if s, ok := meta[MetaCaller].(string); ok && busUser.MatchString(s) { return s } return Unproven } // runAs runs a tool with the caller held for its arguments for as long as it runs. func runAs(t Tool, caller string, args map[string]any) (any, error) { key := argsKey(args) calls.Store(key, caller) defer calls.Delete(key) return t.Run(args) }